Python except many exceptions

How to catch multiple exceptions in Python?

In this tutorial, we’ll cover an important topic in Python programming: catching multiple exceptions in Python. With examples, I will show you, multiple exception handling in Python.

What is Exception Handling in Python?

In Python, an exception is an event that disrupts the normal execution of a program. This could be due to incorrect input, a server not responding, a file not being found, and so on. When these exceptions occur, Python halts the program and generates an error message.

We use try-except blocks to handle these exceptions and prevent our program from stopping abruptly. We’ll write the code that could potentially raise an exception in the try block and the code that handles the exception in the except block in Python.

Catch Multiple Exceptions in Python

In Python, we can catch multiple exceptions in a single except block. This is useful when you have a piece of code that might raise more than one type of exception and want to handle all of them similarly.

Читайте также:  Php ldap filter all

Here’s the basic syntax for catching multiple exceptions:

try: # code that may raise an exception except (ExceptionType1, ExceptionType2, ExceptionType3, . ): # code to handle the exception

Example: Handling multiple exceptions in Python

Let’s say you’re writing a Python program that reads a file and then performs a division operation with the data from the file. This code might raise several exceptions. The open() function might raise a FileNotFoundError if the file doesn’t exist, and the division operation might raise a ZeroDivisionError if you try to divide by zero.

Here’s how you could catch both exceptions in Python with a single except block:

try: file = open("myfile.txt", "r") number = int(file.read()) result = 100 / number except (FileNotFoundError, ZeroDivisionError): print("An error occurred")

In this code, if either a FileNotFoundError or a ZeroDivisionError is raised, the program will print “An error occurred” and continue executing the rest of the program.

However, if you want to execute different code for each exception, you would use separate except blocks:

try: file = open("myfile.txt", "r") number = int(file.read()) result = 100 / number except FileNotFoundError: print("The file was not found") except ZeroDivisionError: print("Cannot divide by zero")

n this example, if a FileNotFoundError is raised, the program will print “The file was not found”. If a ZeroDivisionError is raised, it will print “Cannot divide by zero”.

Another Example:

Let’s consider an example where we have a Python dictionary of user data, and we’re trying to perform some operations that could raise exceptions. The operations include accessing a key that might not exist (raising a KeyError ), and converting a string to an integer (which could raise a ValueError if the string does not represent a valid integer).

user_data = < "name": "John", "age": "25", "balance": "two thousand" # This should have been a numeric string. >try: # Accessing a non-existing key will raise a KeyError. email = user_data["email"] # Converting a non-numeric string to an integer will raise a ValueError. balance = int(user_data["balance"]) except (KeyError, ValueError) as e: print("An error occurred: ", str(e))

In this code, if the key “email” does not exist in the dictionary, a KeyError will be raised. Similarly, when trying to convert the string “two thousand” to an integer, a ValueError will be raised. Both of these exceptions are caught by the except block, and an error message is printed.

Check out the below screenshot for the output.

How to catch multiple exceptions in Python

Using as to access the Exception Object in Python

You can use the as keyword in your except block to access the exception object in Python. This allows you to print the error message associated with the exception, or access its other properties.

try: file = open("myfile.txt", "r") number = int(file.read()) result = 100 / number except (FileNotFoundError, ZeroDivisionError) as e: print("An error occurred: ", str(e))

In this code, if an exception is raised, the program will print “An error occurred: ” followed by the error message associated with the exception.

Conclusion

In this tutorial, we’ve discussed how to handle multiple exceptions in Python using the try-except blocks. This is a powerful tool that allows you to create robust programs that can handle unexpected errors in Python.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

How to Catch Multiple Exceptions in Python

How to Catch Multiple Exceptions in Python

When a program encounters an exception during execution, it is terminated if the exception is not handled. By handling multiple exceptions, a program can respond to different exceptions without terminating it.

In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

There are several approaches for handling multiple exceptions in Python, the most common of which are discussed below.

Using Same Code Block for Multiple Exceptions

With this approach, the same code block is executed if any of the listed exceptions occurs. Here’s an example:

try: name = 'Bob' name += 5 except (NameError, TypeError) as error: print(error) rollbar.report_exc_info()

In the above example, the code in the except block will be executed if any of the listed exceptions occurs. Running the above code raises a TypeError , which is handled by the code, producing the following output:

cannot concatenate 'str' and 'int' objects

Using Different Code Blocks for Multiple Exceptions

If some exceptions need to be handled differently, they can be placed in their own except clause:

try: name = 'Bob' name += 5 except NameError as ne: # Code to handle NameError print(ne) rollbar.report_exc_info() except TypeError as te: # Code to handle TypeError print(te) rollbar.report_exc_info()

In the above example, NameError and TypeError are two possible exceptions in the code, which are handled differently in their own except blocks.

Investigating Exceptions using If, Elif, Else Statements

Exceptions can also be checked using if-elif-else conditions, which can be useful if the exception needs to be investigated further:

import errno try: f = open('/opt/tmp/myfile.txt') except IOError as e: rollbar.report_exc_info() if e.errno == errno.ENOENT: print('File not found') elif e.errno == errno.EACCES: print('Permission denied') else: print e

Here, the variable e holds an instance of the raised IOError . The additional status code of the exception is checked in the if , elif and else blocks and the first match is executed:

Multiple Except Clauses Matching

There may be cases where a piece of code causes an exception that can match multiple except clauses:

try: f = open('/opt/tmp/myfile.txt') except EnvironmentError: rollbar.report_exc_info() print('Failed to open file') except IOError: rollbar.report_exc_info() print('File not found')

Since EnvironmentError is more general than IOError , it matches the exception in the code above. The EnvironmentError except clause is listed first, so the code within it gets executed, producing the following output:

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Sign Up Today!

How to Handle Unhashable Type List Exceptions in Python
How to Throw Exceptions in Python

«Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind.»

Источник

Обработка нескольких исключений в Python

Как записать несколько исключений в одной строке?

В этой статье я расскажу о конструкции try/except, а именно, о том, как вы можете перехватывать несколько исключений в одной строке и как использовать метод suppress().

Введение

Методы, приведённые в статье, помогут вам в написании более доступного и универсального кода, который придерживается принципов DRY (don’t repeat yourself — не повторяться).

Давайте начнем с рассмотрения проблемы:

try: funt_one() except TypeError as e: funt_two() except KeyError as e: funt_two() except IndexError as e: funt_two()

Как вы видите, это очень сырой код. Я повторяю один и тот же вызов несколько раз. Подобные практики могут превратить чтение и рефакторинг вашего кода в настоящий кошмар.

Вместо того чтобы писать исключения одно за другим, лучше сгруппировать все эти обработчики исключений в одну строку!

Несколько исключений

Если вам нужен только быстрый ответ, то все просто: используйте кортеж.

Все ошибки, содержащиеся в кортеже строки исключения, будут оценены вместе:

try: funt_one() except (TypeError, KeyError, IndexError) as e: funt_two()

Как избежать некачественного программирования

«Ошибки никогда не должны проходить бесшумно.» — The Zen of Python.

Предложения try/except, вероятно, являются наиболее часто используемым шаблоном в Python.

Очень заманчиво просто попробовать и сделать голое исключение для проблемы, чтобы «заставить ее уйти». Делая это, мы эффективно сметаем исключения под ковер, что является позором, особенно потому, что они могут быть удивительно полезны для восстановления после потенциально фатальных ошибок или для того, чтобы пролить свет на скрытые ошибки.

Вот почему при использовании предложений except вы всегда должны обязательно указывать ошибки, которые, как вы знаете, могут возникнуть, и исключать те, которые вы не знаете.

Позволить вашей программе потерпеть неудачу — это нормально, даже предпочтительнее, чем просто притворяться, что проблемы не существует.

«Ошибки никогда не должны проходить бесшумно… если только явно не замолчать.» — The Zen of Python.

Однако, если вдруг у вас есть возможность игнорировать обработку исключений, вы можете использовать функцию suppress():

Использование функции suppress

from contextlib import suppress with suppress(TypeError, KeyError, IndexError): func_one()

Метод suppress() принимает в качестве аргумента ряд исключений и выполняет try/except/pass с этими ошибками. Этот метод позволяет вам писать несколько исключений в одной строке.

Такой вариант позволит вам избежать написания try/except/pass вручную:

try: func_one() except (TypeError, KeyError, IndexError) as e: pass

И ещё один плюс — этот метод также стандартен в любой версии Python 3.4 и выше!

Заключение

В этой статье я объяснил, как обрабатывать несколько исключений в одной строке. Я также показал некоторые плохие практики игнорирования исключений и использовал функцию suppress() для явного подавления исключений.

Программирую на Python с 2017 года. Люблю создавать контент, который помогает людям понять сложные вещи. Не представляю жизнь без непрерывного цикла обучения, спорта и чувства юмора.

Ссылка на мой github есть в шапке. Залетай.

Источник

Оцените статью