In this tutorial, we’ll learn Python exception handling in detail. We’ll going through multiple examples to understand how to handle exceptions in Python language.
- Introduction: Python Exception Handling
- Handle Exceptions Using try, except, finally
- Example 1: Not Using Python Exception Handling
- Example 2: Using Python Exception Handling (try, except)
- Example 3: Handling Specific Exceptions
- Example 4: try, except, finally
Introduction: Python Exception Handling
In Python, there are cases when we run the code and it throws an exception. Python has many built-in exceptions that are raised for specific errors.
When an exception occurs, the Python interpreter terminates the current process and passes it to the caller. The program will crash if its not handled.
We’ll learn how to catch the exceptions and print our own custom error messages when an exception occurs.
Handle Exceptions Using try, except, finally
These are used for Python exception handling.
- In try block, we specify the code that might cause an exception.
- In except block, we can specify our own custom error message or can execute some other actions.
- Finally block will run regardless of the state. It means it’ll run whether the exception occurs or not.
let’s first see what we’ll get if we don’t use Python exception handling.
Example 1: Not Using Python Exception Handling
a=5; b='6'; print(a+b)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The above code raised a type exception as we’ve tried to add an integer and a string. The above output block shows the exception that is being raised.
Let’s now try the same code with Python exception handling.
Example 2: Using Python Exception Handling (try, except)
a=5; b='6'; try: print(a+b) except: print('Please add values of type integers only')
Please add values of type integers only
In the above Python code, we’ve specified the statement that raised the exception in try block and in except block, we just have specified a simple print statement. When the code runs, the exception occurs so the control will jump from try block to except block and run its content. As a result, the print statement gets executed.
We can also specify the except block in which each type of error will be shown explicitly. See below examples:
a=5; b='6'; try: print(a+b) except Exception as e: print(e)
unsupported operand type(s) for +: 'int' and 'str'
a=5; b='6'; try: print(a/0) except Exception as e: print(e)
division by zero
You can try it with other error types as well.
Example 3: Handling Specific Exceptions
In the above code, except block will execute no matter which type of exception occurs. Although, we can specify different except block for different type of exceptions. See below code:
a=5; b='6'; lst=[1,2,3] try: print(a+b) except TypeError: print('Please don't add integer with string') except ZeroDivisionError: print('Please don\'t divide value with 0') except IndexError: print('Please specify values within the range only')
Please don't add integer with string
- We’ve specified 3 different except blocks with their own specific types.
- In try block, we’ve tried to add integer to a string which raised a type error exception. So it’ll check for the except block specified with type error and if found, then it’ll run its content as seen in the above output.
Let’s now divide the value with 0 and see which block will get executed. See below code:
try: print(a/0) // use it in the above code
Please don't divide value with 0
We’ve just used the try statement here to avoid bulkiness of code. Assume that its written it the above code block. Now a zero division error occurs, so it’ll check for the except block specified for that error and will run its content, if found.
Let’s now try to print index value of specified simple Python list greater than the range specified and see which block will get executed. See below code:
try: print(lst) // use it in the above code block
Please specify values within the range only
We can see that index error occurs so the except block specified for index error gets executed.
Just keep in mind that if we’ve specified all the except blocks with specific error type and an exception occurs which is not specified then it’ll be thrown unhandled. For instance, we’ve specified a type error except block only and the exception is of zero division error then it’ll be thrown unhandled.
Example 4: try, except, finally
Let’s now specify the finally block as well. It’ll get executed no matter if the exception occurs or not. See below examples.
a=5; b='6'; try: print(b+a) // one string and one integer except TypeError: print('Type error occurs.') finally: print('Program finishes.')
Type error occurs. Program finishes.
a=5; b=6; try: print(b+a) // both are integers except TypeError: print('Type error occurs.') finally: print('Program finishes.')
11 Program finishes.
We can see that finally block always gets executed. So this is how Python exception handling works. Click here if you want to learn more about it. Also, try it without except block or just try and finally and see the results.
I’d be glad to see you share this post with your developer friends.
Don’t hesitate to ask if you still have any questions regarding Python exception handling. I’ll be very happy to answer all your questions.
To conclude this tutorial, hope you now have a detailed practical knowledge of Python exception handling. I’ll be very happy to receive your feedback on this post.
Do visit my other articles on Python programming. Links to some of them are listed below. Others can be found using the navigation bar or search box of this site. Thank you for reading this post.
You may like to read:
[Solved] How To Write File In Python
[3 Ways] How To Easily Format String In Python
How To Easily Use Python String Split Method [Detailed Python Guide]
[Solved] How To Convert Python Tuple To String
[Solved] How To Find Maximum Value In Python Tuple
How To Easily Get Input In Python [Python Code Examples]
How To Easily Reverse String In Python [Python Code Examples]