What is Exception Handling?
When executing Python code, different errors may occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Python’s default exception-handling behavior kicks in: it stops the program and prints an error message.
If you don’t want this default behavior, you need to handle these exceptions.
The try and except Block
In Python, exceptions are handled using the
- try: Run this code as a normal part of the program
- except: Execute this code when there is an exception
Python executes the
try block as a normal part of the program.
When an error occurs during its execution, the rest of the block is skipped and
except block is executed.
In below example, the
try block will generate an exception, because a number is divided by zero.
except block will be executed.
try: x = 1/0 except: print('Something went wrong.')
Something went wrong.
Python don’t just handle exceptions if they occur immediately in the
try block, but also if they occur inside functions that are called in the
def this_fails(): x = 1/0 try: this_fails() except Exception as e: print(e)
division by zero
Catch Multiple Exceptions
You can define as many
except blocks as you want, to catch and handle specific exceptions.
Example: Print one message for ZeroDivisionError and another for all other errors
try: x = 1/0 except ZeroDivisionError: print('Attempt to divide by zero') except: print('Something else went wrong')
Attempt to divide by zero
If you want to execute the same block of code for multiple exceptions, specify all the exceptions in a parenthesized tuple.
Example: Execute same block of code for multiple exceptions
try: x = 1/0 except (ZeroDivisionError, ValueError): print('ZeroDivisionError or ValueError is raised') except: print('Something else went wrong')
ZeroDivisionError or ValueError is raised
The Else Clause
The try…except block has an optional
else clause is executed only if no exceptions are raised.
try: x = 1/1 except: print('Something went wrong') else: print('Nothing went wrong')
Nothing went wrong
The Finally Clause
The try…except block has another optional
finally clause is always executed, whether an exception has occurred or not.
Example: finally clause is always executed
try: x = 1/0 except: print('Something went wrong') finally: print('Always execute this')
Something went wrong Always execute this
finally clause to define clean-up actions that must be executed under all circumstances e.g. closing a file.
Example: Exception handling during file manipulation
try: f = open('myfile.txt') print(f.read()) except: print("Something went wrong") finally: f. close()
Raising an Exception
If you want to raise an exception when a certain condition occurs, use raise keyword.
Example: Raise built-in exception ‘NameError’
raise NameError('An exception occured!')
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: An exception occured!
You can create your own exceptions by creating a new exception class like this:
Example: Create and raise Custom exception ‘InputError’
class InputError(Exception): pass raise InputError('Custom exception')
Traceback (most recent call last): File "<stdin>", line 4, in <module> InputError: Custom exception
Custom exceptions should typically be derived from the Exception class.