How to Catch Multiple Exceptions in Python
Last updated
Last updated
Python exception handling allows you to halt a program when an unforeseen error occurs. You then prompt the program to follow your instructions for resolving the error instead of letting it crash. An exception is raised when a runtime error occurs during execution. Examples include ZeroDivisionError (when dividing by zero) and SyntaxError (when the program uses incorrect syntax). The error message displayed will indicate what kind of exception was encountered.
The try block
The try block is a section of code that may raise an exception. If an exception occurs, the except block executes to handle it. The except block can catch multiple exceptions by naming them in a tuple. This allows the programmer to customize what happens when an exception is raised.
The except block can also catch exceptions that occur inside the functions called in the try block. For example, if the function f calls g with an argument of 50, and the index of g is out of range, the except block will catch the IndexError. You cannot have more than one except block with the same name of an exception as this would cause a syntax error. You can however compliment all the specific except blocks with a generic except block which will serve to handle any exception that goes unhandled by the other ones. This way you can avoid duplication of code. The last block which is executed once control from the try block exits is the finally block which closes any resources that might have been opened by the try and catch blocks.
The except block
The except block catches the exceptions that are raised outside of the try block. It’s important to have a few except blocks for the different types of errors that you expect. Some common exceptions include IndexError, KeyError, EOFError (EOF while opening a file), ValueError, ArithmeticError and FloatingPointError.
The finally block
The finally block is executed whenever control exits the try or catch block due to a return, break, continue, or exception thrown from the try or catch blocks. If no catch block handles an exception, the code in a finally block still executes.
Python doesn’t only handle exceptions that occur immediately inside the try block, but also any functions that are called (even indirectly) from within the try block. In this example, f calls g and that function raises an IndexError, which might not be caught by any of the except blocks.
The finally block allows you to write clean-up actions that will always be executed, regardless of whether an exception is thrown or not. For example, you can use a finally block to close any open streams in your program. This ensures that any input and output streams are closed properly, no matter what happens in the try or catch blocks. It also prevents an exception from being rethrown when the finally block is executed, because that would make the finally block’s return statement inconsistent with its surrounding code.
The nested except block
Using multiple except blocks is one way to handle exceptions in Python. However, it can be difficult to read the code because of all the try-catch block nesting. Using nested except blocks can also result in unhandled exceptions, which may cause the program to terminate prematurely or produce unwanted results.
The except block encloses the code that might raise an error, and the interpreter checks to see if any of the except blocks can handle the exception that was raised. If the exception is not handled, the interpreter stops and generates an error message. The except block can include an else clause, which is executed if no exception is raised. It is also possible to use a finally block, which is always executed, regardless of whether or not an exception is raised. This is useful for cleaning up after code execution, such as closing a file object.
The code in the try block is executed and if no exception occurs, the except clause is skipped. If an exception is raised, will check the exception handlers in the order that they were declared and look for an except clause with a matching exception type. The except block can also contain clean-up code that is executed regardless of the result of the try and except blocks. This can include logging the exceptions or redirecting the user to an error page. Another option is to use the pass statement, which passes the exception on to the next handler. This is a good choice when you need to keep the flow of the program intact.