Python Try Except Example
Hello in this tutorial, we will explain how to use the Try Except block in Python programming.
1. Introduction
The try-except
block in python is used to handle exceptions in python code. It is represented by the following syntax:
try: # Some Code except: # Executed if an error in the # try block else: # execute if no exception finally: # Some code ..... (always executed)
In this tutorial, we will focus on the try-except
block in python and play around with it.
1.1 Setting up Python
If someone needs to go through the Python installation on Windows, please watch this link. You can also download it from this link.
2. Python Try-Except Example
I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.
2.1 Creating an implementation file
Add the below code to the python script. The script contains several methods that will help understand the try-except
block. You’re free to play around with these methods as per your wish.
- The
divide()
method will return the exception message when the division fails - The
multi_catch()
method will help understand a scenario when a function may throw multiple types of exceptions depending on the arguments, logic, etc - The
divide_with_else()
method will help define a block of code that will be executed if no exception is thrown - The
divide_with_finally()
method will be executed regardless if thetry
block throws an exception or not - The
raise_exception()
method will help raise an exception in the code if a condition occurs
jcg-assignment-tryexcept-example.py
""" try: # Some Code except: # Executed if an error in the # try block else: # execute if no exception finally: # Some code .....(always executed) """ def divide(x, y): try: result = x / y print('result = {}'.format(result)) except ZeroDivisionError as zde: print('some err has occurred.') print(zde) def multi_catch(): try: print('1' + 1) print(1 / 0) except NameError: print('name err has occurred.') except ZeroDivisionError: print('cannot divide by zero') except: print('unknown error') def divide_with_else(x, y): try: result = x / y except ZeroDivisionError as zde: print(zde) else: print('result = {}'.format(result)) def divide_with_finally(x, y): try: result = x / y except ZeroDivisionError as zde: print('some err has occurred.') print(zde) else: print('result = {}'.format(result)) finally: print('done') def raise_exception(x): if x < 0: raise Exception('Invalid number entered') if __name__ == '__main__': divide(1, 0) print('\n') multi_catch() print('\n') divide_with_else(6, 3) print('\n') divide_with_finally(10, 2) print('\n') raise_exception(-1)
Run this script and if everything goes well the output will be shown in the IDE console.
Console output
some err has occurred. division by zero unknown error result = 2.0 result = 5.0 done Traceback (most recent call last): File "C:\Users\yatin.batra\mycode\python-programming\aws\jcg-python-assignments\jcg-assignment-tryexcept-example.py", line 70, in raise_exception(-1) File "C:\Users\yatin.batra\mycode\python-programming\aws\jcg-python-assignments\jcg-assignment-tryexcept-example.py", line 58, in raise_exception raise Exception('Invalid number entered') Exception: Invalid number entered
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
3. Summary
In this tutorial, we learned about the try-except block in python programming. You can download the source code of this tutorial from the Downloads section.
4. Download the Project
This was a tutorial on how to use the Try-Except
block in Python.
You can download the full source code of this example here: Python Try Except Example
Last updated on Jan. 31st, 2022