If you want to learn Python exception handling, read this tutorial. It should help you master the use of try-except and try-finally statements in your programs. Go through the examples given to get started quickly. Exception handling is very critical for creating robust and stable applications. And it encourages programmers to write clean, readable, and error-free code.
You would agree that even the best of the code could behave unexpectedly at runtime. It could be due to a missing configuration, a change in the execution environment, or the user entering the wrong input. Some of these errors may cause the program to terminate abruptly. With the help of exception handling, you can manage such issues and avoid intermittent failures of your code. So, let’s begin this tutorial by first understanding the difference between an error and an exception. Consequently, we’ll teach you the essentials of Python exception handling.
Python Error Vs Exception
An error is something that goes wrong in the program, e.g., a syntactical error.
It occurs at compile time. Let’s see an example.
if a<5 File "<interactive input>", line 1 if a < 5 ^ SyntaxError: invalid syntax
The errors also occur at runtime, and we know them as exceptions. An exception is an event that occurs during the execution of a program and disrupts the normal flow of the program’s instructions.
In general, when a Python script encounters an error situation that it can’t cope with, it raises an exception.
When a Python script raises an exception, it creates an exception object.
Usually, the script handles the exception immediately. If it doesn’t do so, then the program will terminate and print a traceback to the error along with its whereabouts.
>>> 1 / 0 Traceback (most recent call last): File "<string>", line 301, in run code File "<interactive input>", line 1, in <module> ZeroDivisionError: division by zero
How to Use Try-Except?
We use the try-except statement to enable exception handling in Python programs.
Inside the try block, you write the code which can raise an exception.
And the code that handles or catches the exception, we place in the except clause.
Python Exception Handling Syntax
Following is the syntax of a Python try-except-else block.
try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no exception then execute this block.
Meanwhile, have a look at our 30 Python Interview Questions designed for beginners!
Here is a checklist for using the Python try statement effectively.
- A single try statement can have multiple except statements depending on the requirement. In this case, a try block contains statements that can throw different types of exceptions.
- We can also add a generic except clause which can handle all possible types of exceptions.
- We can even include an else clause after the except clause. The instructions in the else block will execute if the code in the try block doesn’t raise an exception.
Try-Except Examples
Python sample code to understand the use of Python try-except.
try: fob = open("test", "w") fob.write("This is my test file for exception handling!!") except IOError: print("Error: can't find the file or read data") else: print("Write operation is performed successfully on the file") fob.close()
The above code produces the following output.
# Output # Write operation is performed successfully on the file.
Let’s take another example in which we are trying to open a file in the READ mode.
We’ll perform a WRITE operation on it. Upon execution, it’ll throw an exception.
try: fob = open("test", "r") fob.write("It's my test file to verify exception handling in Python!!") except IOError: print("Error: can't find the file or read data") else: print("Write operation is performed successfully on the file")
The above code produces the following output.
# Output # Error: can't find file or read data
Handle All Types of Exceptions
If we use a bare “except” clause, then it would catch all types of exceptions.
However, neither it’s a good programming practice nor does anyone recommend it.
It is because such a Python try-except block can handle all types of exceptions. But it’ll not help the programmer to find what exception caused the issue.
You can go through the below code to see how to catch all exceptions.
Python Pseud Code to Catch All Exceptions
try: You do your operations here; ...................... except: If there is any exception, then execute this block. ...................... else: If there is no exception then execute this block.
Handle Multiple Exceptions
We can define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under the except clause.
In short, when we define except clause in this way, we expect the same piece of code to throw different exceptions. Also, we want to take the same action in each case.
Please refer to the below example.
Python Pseudo Code to Catch Multiple Exceptions
try: You do your operations here; ...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ...................... else: If there is no exception then execute this block
How to Use Try-Finally?
We can also enable Python exception handling with the help of try-finally statements.
With the try block, we also have the option to define the “finally” block. This clause allows defining statements that we want to execute, no matter whether the try block has raised an exception or not.
This feature usually comes into the picture while releasing external resources.
Here is the coding snippet for help.
try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
Try-Finally Examples
One critical point is that we can either define an “except” or a “finally” clause with every try block. You can’t club these together. Also, you shouldn’t use the “else” clause along with a “finally” clause.
Let’s take an example to get more clarity.
try: fob = open('test', 'w') fob.write("It's my test file to verify try-finally in exception handling!!") print('try block executed') finally: fob.close() print('finally block executed')
If the exception doesn’t occur, then you’ll see the following output.
""" Output try block executed finally block executed """
Suppose we open the file in the READ mode and then try to perform a write operation on it. In such a situation, the below code will help to handle the exception.
try: fob = open('test', 'r') try: fob.write("It's my test file to verify try-finally in exception handling!!") print('try block executed') finally: fob.close() print('finally block executed to close the file') except IOError: print("Error: can't find file or read data")
In this case, the interpreter will raise an exception, and the following output will get displayed.
""" Output finally block executed to close the file Error: can't find file or read data """
When some code causes an exception in a try block, the execution immediately passes to the “finally” block. After all the statements in the “finally” block get executed, the exception resumes to the “except” block for execution. But there must present a next higher layer of the “try-except” statement.
Raise Exceptions with Arguments
What does the raise keyword do in Python?
We can forcefully raise an exception using the raise keyword.
We can also optionally pass values to the exception and specify why it has occurred.
Here is the syntax for calling the “raise” method.
raise [Exception [, args [, traceback]]]
Where,
- Under the “Exception” – specify its name.
- The “args” is optional and represents the value of the exception argument.
- The final argument, “traceback,” is also optional and if present, is the traceback object used for the exception.
Let’s take an example to clarify this.
Raising Exception Example
>>> raise MemoryError Traceback (most recent call last): ... MemoryError >>> raise MemoryError("This is an argument") Traceback (most recent call last): ... MemoryError: This is an argument >>> try: a = int(input("Enter a positive integer value: ")) if a <= 0: raise ValueError("This is not a positive number!!") except ValueError as ve: print(ve) Following Output is displayed if we enter a negative number: Enter a positive integer: –5 This is not a positive number!!
Custom Exceptions in Python
A custom exception is one which the programmer creates himself.
He does it by adding a new class. The trick here is to derive the custom exception class from the base exception class.
Most of the built-in exceptions do also have a corresponding class.
Create Exception Class in Python
>>> class UserDefinedError(Exception): ... pass >>> raise UserDefinedError Traceback (most recent call last): ... __main__.UserDefinedError >>> raise UserDefinedError("An error occurred") Traceback (most recent call last): ... __main__.UserDefinedError: An error occurred
In the above code snippet, you can see that we have created a user-defined exception class, the “UserDefinedError.” It is using the base Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does, i.e., by calling the “raise” statement with an optional error message.
Let’s take an example.
Custom Exception Example
In this example, we will show how to raise a user-defined exception and catch errors in a program.
This program prompts the user to enter an alphabet again and again until he inputs the stored alphabet only.
For help, the program provides a hint to the user so that he can figure out the correct alphabet. Also, he can check whether his guess is higher or less than the stored alphabet.
#define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class InputTooSmallError(Error): """Raised when the entered alpahbet is smaller than the actual one""" pass class InputTooLargeError(Error): """Raised when the entered alpahbet is larger than the actual one""" pass #our main program #user guesses an alphabet until he/she gets it right #you need to guess this alphabet alphabet = 'm' while True: try: apb = input("Enter an alphabet: ") if apb < alphabet: raise InputTooSmallError elif apb > alphabet: raise InputTooLargeError break except InputTooSmallError: print("The entered alphabet is too small, try again!") print('') except InputTooLargeError: print("The entered alphabet is too large, try again!") print('') print("Congratulations! You guessed it correctly.")
Let’s test this program by supplying different inputs.
Enter an alphabet: s This value is too large, try again! Enter an alphabet: a This value is too small, try again! Enter an alphabet: l This value is too small, try again! Enter an alphabet: p This value is too large, try again! Enter a number: m Congratulations! You guessed it correctly.
Thus you can see that we have defined a base class called Error here in this program. It raises two exceptions (“InputTooSmallError” and “InputTooLargeError“) derived from the base class. It’s the standard way to define user-defined exceptions in Python programming.
Python Built-in Exceptions
Exception | Cause of Error |
---|---|
AirthmeticError | For errors in numeric calculation. |
AssertionError | If the assert statement fails. |
AttributeError | When an attribute assignment or the reference fails. |
EOFError | If there is no input or the file pointer is at EOF. |
Exception | It is the base class for all exceptions. |
EnvironmentError | For errors that occur outside the Python environment. |
FloatingPointError | It occurs when the floating point operation fails. |
GeneratorExit | If a generator’s <close()> method gets called. |
ImportError | It occurs when the imported module is not available. |
IOError | If an input/output operation fails. |
IndexError | When the index of a sequence is out of range. |
KeyError | If the specified key is not available in the dictionary. |
KeyboardInterrupt | When the user hits an interrupt key (Ctrl+c or delete). |
MemoryError | If an operation runs out of memory. |
NameError | When a variable is not available in the local or global scope. |
NotImplementedError | If an abstract method isn’t available. |
OSError | When a system operation fails. |
OverflowError | It occurs if the result of an arithmetic operation exceeds the range. |
ReferenceError | When a weak reference proxy accesses a garbage-collected reference. |
RuntimeError | If the generated error doesn’t fall under any category. |
StandardError | It is a base class for all built-in exceptions except <StopIteration> and <SystemExit>. |
StopIteration | The <next()> function has no further item to be returned. |
SyntaxError | For errors in Python syntax. |
IndentationError | It occurs if the indentation is not proper. |
TabError | For inconsistent tabs and spaces. |
SystemError | When the interpreter detects an internal error. |
SystemExit | The <sys.exit()> function raises it. |
TypeError | When a function is using an object of the incorrect type. |
UnboundLocalError | If the code using an unassigned reference gets executed. |
UnicodeError | For a Unicode encoding or decoding error. |
ValueError | When a function receives invalid values. |
ZeroDivisionError | If the second operand of division or modulo operation is zero. |
Summary – Python Exception Handling Concepts
Most of the time, we aim to discover a topic that can help our readers in their work. That’s why we covered this tutorial on Python Exception Handling.
It would be great to hear from you if this post helped you in learning an essential concept of Python. Do let us know about your experience.
If you liked the post, then please don’t miss to share it with friends and on social media.
Teaching is the best asset that a person should share without any cost.
Keep Learning,
TechBeamers.