In this tutorial, you’ll learn how to define,
catch and exception handling in python – with a few examples.
We’ll be covering the following topics in this tutorial:
Exceptions Handling in Python
In Python, different errors may occur while executing a code due to incorrect input or even other unpredictable errors. Where the program encounters an error and something goes wrong with the program, the Python interpreter interrupts the current process and moves it over to the calling process – before it handles.
It is Python’s default exception-handling behavior. If not handled, the program crashes automatically and prints an error code. You must handle the exceptions in your program if you do not want this default action. And that’s where
try..except blocks come in.
Exception handling in Python is a technique of processing problems that occur during the execution of the program. Using exception handling, we can test the code and avoid it from exiting abruptly.
You may make certain mistakes when developing a program that leads to errors while trying to execute it. During its execution, Python program stop working as soon as it encounters an error, that is not handled. These errors categorize into two categories:
syntax errors and
logical errors – often called Exceptions.
Python Syntax Errors
Syntax errors or parsing errors are triggered by not observing the correct structure of the program. The most basic form of error is a
Syntax error. They occur when the Python parser cannot interpret a code line. Many syntax errors are typos, incomplete or incorrect arguments. If you get this error, try to look at the code for one of these keywords:
for action in ["alpha ", "beta", "gamma"] ^ SyntaxError: invalid syntax
Python Logical Errors (Exceptions)
After passing the syntax check, errors that occur during runtime are called logical or
exceptions errors. It is the most challenging type of error since it gives unexpected results and can crash the program. Many different things will arise if Logical error encounters. Whenever such errors occur, Python generates an Exception object. Exceptions occur where the python parser understands what to do with this piece of code but cannot do it. Example: attempting to reach the Internet without an internet connection: the Python interpreter knows but cannot execute the instruction.
Illegal operations will also raise Exceptions. Python includes several built-in exceptions when the following errors occur:
ImportError – and so on. Consequently, Python prints the
Traceback of the error if not correctly handled. And in the last line of the message, what sort of exception in the program has encountered, along with specifics of what error caused.
for i in [10, 20, 30]: print(i / 0) Traceback (most recent call last): File "<stdin>", line 2, in <module> ZeroDivisionError: division by zero
Fortunately, these exceptions may catch and handle, and then the program adapted such that it does not crash. In Python, you can even define your exceptions if needed! After looking at the variations between syntax errors and exceptions, go ahead and see how to raise, catch, and handle these exceptions in Python.
Instead of waiting for a program to crash, you may also begin by creating an assertion in Python and check if a specified requirement has been fulfilled. If this is true, so that is excellent – the program carries ahead. But if the situation proves false, the program can throw an exception from
Let’s have a look at the illustration below where the asserted the code on a Linux system:
import sys assert ('linux' in sys.platform), "This code runs on Linux only."
If you run this code on a Linux machine, the assertion goes through. The outcome of the assertion would be
false if you were to run this code on a Windows machine or somewhere else, and the result would be as follows:
Traceback (most recent call last): File "<input>", line 2, in <module> AssertionError: This code runs on Linux only.
The last thing the program does is throw an
AssertionError exception. The program stops and does not proceed. Still, What if you don’t like that?! Then you’re going to have to catch this exemption.
Python Try … Except
When there is an error: Python will typically throw an exception, create an error message, and interrupt the program if this exception is not correctly handled. When it arises, and within the try block, the try block’s remainder ignore when this error is found, and the exceptional block is executed.
Catch ALL Exceptions
When an error occurs: Python would normally throw an exception, generate an error message, and stop the program if this exception is not handled correctly. When this error occurs during its execution – and inside the try statement – the rest of the try block is skipped as soon as this error is encountered, and the except block is executed.
try: statement_1 statement_fail statement_not_executed except: print('Something went wrong!')
except block in Python used to catch and handle all exceptions. Python will execute the code following the try block until an exception encounter. The code that follows the except block determines how your program responds to exceptions. Consequently, the except block use to catch and handle the exceptions encountered in the try block.
try: statement_1 statement_fail statement_not_executed except Exception as error: print('Something went wrong:', error)
So, if you don’t want to run the same code block with every exception? Fortunately, Python provides you with the ability to catch one or more exceptions at a time. Let’s explore
Catch Single Exception
We did not mention a particular exception in the previous example except block. It is not a good programming technique, so it catches all exceptions irrespective of your error and handles all exceptions in the same manner. Nevertheless, you should define the exceptions from a clause other than that:
try: x = 1/0 statement_not_executed except ZeroDivisionError: print('Something went wrong!')
In the case above, the try block creates an exception since it divides a number by zero. Therefore the
ZeroDivisionError except block is only performed for this particular error – in this situation, no other errors can handle, and your program can crash.
That’s fine, but you wonder: how can you handle in Python with several exceptions? This is the answer
Catch Multiple Exceptions
A try clause can have any number of except block to handle different exceptions. However, only one will be executed in case an exception occurs. Consequently, you should describe as many except blocks as you want – so that you can independently and differently catch and handle unique exceptions.
try: x = 1/0 except ZeroDivisionError: print('Attempt to divide by zero') except: print('Something else went wrong')
And if you choose to run the same block of code for many exceptions, specify ALL exceptions inside a tuple :
try: x = 1/0 except TypeError: print('TypeError is raised') except (ZeroDivisionError, ValueError): print('ZeroDivisionError or ValueError is raised') except: print('Something else went wrong')
Python handles exceptions not only when they occur in the
try block, If an error arises, and you don’t know how to handle it correctly, then
"pass" keyword should be used to avoid a crash of your program.
def division_by_zero(): x = 1/0 try: division_by_zero() except Exception as e: print('Attempt to divide by zero') pass next_statement_executed
Your program won’t crash any more because all exceptions raised during its execution can be caught and handled! How can you execute a code block only if there were no exceptions to the try clause?
Python Else Clause
In certain cases, you would want to run a certain code within the try clause that was error-free. In such instances, the optional else keyword with the try statement may be used to define a code block to be executed if and only no errors have been raised.
try: x = 1/1 except: print('Something went wrong') else: print('Nothing went wrong')
Here’s an example that divides the integer 1 by 1 and saves the result in variable
x. If an error occurs during this phase, an exception is raised. This error will be caught and handled by the except clause – output
'Something went wrong.' else, it will output
'Nothing went wrong' so there are no exceptions to this program and the else clause was applied.
Python Finally Clause
try..except statement in Python has another and optional finally clause. If specified, the
finally block will always be executed – regardless of whether the try block raises an error or not, and under any circumstances.
try: x = 1/0 except: print('Something went wrong') finally: print('Always execute this')
Imagine you would still take steps to clean up after the code is executed. Python helps you to do so by utilizing the finally clause.
f = open('file.txt') try: print(f.read()) except: print("Something went wrong") finally: f.close()
Raising an Exception
In Python programming, exceptions are raised runtime. But, as a Python developer, you manually throw an exception at any time. To raise such an exception, use the
"raise" reserved keyword.
A customized exemption may follow this statement. Optionally you should specify what type of error to arise and pass the exception values to explain that the exception has been raised. And the machine pauses and shows the exception to the panel – providing clues to what went wrong and debugged.
# Raise built-in exception 'NameError' raise NameError('An exception occured!') # Output: # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # NameError: An exception occured!
Users may define customized exceptions in Python by creating a new class. This exception class must be obtained from the built-in Exception class, explicitly or implicitly. Some of the exceptions included are also drawn from this class.
Here, we have created a user-defined
CustomError exception, which inherits from the exception class. Like any other exceptions, this new exception can be raised using the raise statement – and with an
optional error message.
class CustomError(Exception): pass raise CustomError raise CustomError("A custom error occurred") # Traceback (most recent call last): # File "<stdin>", line 4, in <module> # CustomError: A custom error occurred