With the help of examples, we’ll explore how to manage exceptions in your Python program using try, except, and finally statements. The try block allows you to check for mistakes in a code block. You can handle the error with the except block. When there is no error, the else block allows you to run code. Finally, regardless of the outcome of the try and except blocks, the finally block will enable you to run code.
Syntax errors and exceptions are the two forms of errors in Python. Errors are issues in a program that causes the program to halt its execution. On the other hand, exceptions are raised when internal events disrupt the program’s usual flow.
The following are some examples of frequent Exception Errors:
- If you cannot open the file, you’ll get an IOError.
- When the user presses an unrequired key, the keyboard is interrupted, leading to a KeyboardInterrupt error.
- When a built-in function receives an invalid argument, a ValueError occurs.
- If you hit End-Of-File without reading any data, you’ll get an EOFError.
- If it cannot locate the module, it will throw an importError.
Python will generally pause and generate an error message when an error, or exception, occurs. The try statement is used to handle specific exceptions. Consider a software in which the first function calls the second function, which calls the third function. If an exception occurs in the third function but isn’t handled there, it is passed to the second function, passing it to the first function. On the off chance that this error is not addressed, an error notice appears, and our program comes to an abrupt halt.
Exceptions in Python are handled with the try statement. The try clause contains the critical operation that can cause an exception. The except clause includes the code that handles exceptions.
What is the purpose of try()?
The try clause is the code between the try and except clauses. If there is no exception, only the try clause will be executed unless the clause is already complete. The try clause is bypassed if an exception occurs, and the except clause is executed instead.
If an error occurs, but the code’s except clause fails to handle it, the exception is sent to the outer try statements. The execution will come to a halt if the exception is not handled. There can be more than one clause in a try statement. As a result, we may choose which operations to conduct once the exception has been caught.
Here’s an easy example.
try: print(x) except: print("An exception occurred")
In the example above, because x isn’t defined, the try block will throw an exception. Further, since the try block returns an error, the except block is used instead. The program will crash if the try block is not used, raising an error.
Example: importing the module sys to get the type of exception
import sys random_list = ['w', 5, 9] for entry in random_list: try: print("new entry: ", entry) r = 1/int(entry) break except: print("Oops!", sys.exc_info(), "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
We cycle through the values of the random_list list in the above application sample. Note that the try block has the code that produces an exception, as indicated earlier.
If no exception exists, the except block is bypassed, and normal flow resumes for the last value. If an exception happens, the except block will catch it for the values first and second.
By engaging the exc_info() function, we print the name of the exception—the latter function in the sys module. In addition, 0 causes ZeroDivisionError and causes ValueError because every exception in Python is derived from the fundamental Exception class.
Because x is not specified, this statement will result in an error:
You can create as many exception blocks as you like, for example, if you want to run a unique piece of code in response to a specific error. For instance, If the try block raises a NameError, print one message; otherwise, print another:
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")
If no errors are raised, you can use the else keyword to define a block of code that will be executed. The try block does not produce any errors in this example:
try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong")
Python Catching Specific Exceptions
We didn’t identify any specific exceptions except the clause in the previous example. It isn’t an intelligent programming design since it captures every exception and treats each instance differently. In addition, we indicate the kind of exceptions to be caught using an except clause.
If an exception occurs, a try clause can have any number of except clauses to handle distinct occurrences, but only one is performed. We can declare several exceptions in an except clause using a tuple of values. The following is an example of pseudo-code.
try: # code executes here pass except ValueError: # handle ValueError exception pass except (TypeError, ZeroDivisionError): # handle multiple exceptions # TypeError and ZeroDivisionError pass except: # handle all other exceptions pass
A ‘finally’ clause is added to the try statement in Python. The clause executes always. Furthermore, it is often used in releasing resources from an external point of view. For instance, various dynamic situations like a Graphical User Interface or working with a file while connecting to a remote data center using the network.
Regardless of the program ran successfully or not, we have to clear up the resource before the program comes to a halt. To ensure execution, these activities, such as closing a file, launching a GUI, or disconnecting from the network, are performed in the finally clause.
If the finally block is supplied, it is executed regardless of whether or not the try block returns an error.
try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished")
To close objects and clear up resources, use this method. For example, attempt to open and write to a non-writable file:
try: f = open("demo_file.txt") try: f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close() except: print("Something went wrong when opening the file")
Without leaving the file object open, the program can continue. Even though an exception occurs during program execution, this type of construction ensures that the file is closed.
Raising an exception
If a condition occurs, you can opt to throw an exception as a Python developer. The raise keyword is used to throw (or raise) an exception. If x is less than 0, raise an error and terminate the program:
x = -1 if x < 0: raise Exception("Sorry, cannot accept numbers under zero")
To raise an exception, use the raise keyword. You can specify the type of error to be raised and the text to be printed to the user.
Example: If x is not an integer, throw a TypeError:
x = "codeunderscored" if not type(x) is int: raise TypeError("can only accept integers")
Below is a list of Python’s built-in exceptions. This list indicates which exceptions are thrown and why they are thrown (raised).
- AssertionError -occurs if assert statement fails.
- AttributeError – AttributeError results if reference fails or there is attribute assignment.
- EOFError – results from the input() function hitting the end-of-file condition.
- FloatingPointError-if a floating-point operation fails, then we have a FloatingPointError.
- NameError – NameError occurs because a variable is not found in the global or local scope.
- NotImplementedError – Happens when abstract methods come into play.
- OSError- is an operation in the system causing the system-related error.
- OverflowError – if the result of an arithmetic operation is too large to be represented.
- ReferenceError – if a weak reference proxy finds an application to access a garbage collected referent.
- RuntimeError -is the resultant error if an error does not fall under any other category.
- StopIteration – by next() function to indicate that there is no additional item to be returned by the iterator.
- SyntaxError -by parser on the off chance that the syntax error is encountered.
- IndentationError if there is incorrect indentation.
- TabError – if indentation consists of inconsistent tabs and spaces.
- SystemError – if interpreter detects the internal error.
- SystemExit – by sys.exit() function.
- GeneratorExit – The error is raised if the close() method of the generator is called.
- ImportError – ImportError results from the imported module not being found.
- IndexError- It occurs when the sequence’s index is out of range.
- KeyError – Results from a key missing from a dictionary.
- KeyboardInterrupt- if the user hits the interrupt key, which is either Ctrl+c or delete.
- MemoryError – is due to an operation running out of memory.
- TypeError – if a function or operation is applied to an object of the incorrect type.
- UnboundLocalError – raised if a reference is made to a local variable in a function or method. But no value has been bound to that variable.
- UnicodeError – if a Unicode-related encoding or decoding error occurs.
- UnicodeEncodeError -if a Unicode-related error occurs during encoding.
- UnicodeDecodeError – if a Unicode-related error occurs during decoding.
- UnicodeTranslateError – if a Unicode-related error occurs during translating.
- ValueError – if a function gets argument of correct type but improper value.
- ZeroDivisionError – if the second operand of division or modulo operation is zero.
Exceptions declared by the user
There are many different forms of exceptions in Python. However, they may not always be helpful. Exceptions in your software can be of any type. You must develop a class inherited from Exception to create a user-defined exception.
class UserError(Exception): pass raise UserError("This is the user-defined error!")
In the code above, you created a user-defined exception named UserError. If a mistake happens, you can raise this new exception. The following is the output of your custom error:
Many user-defined exceptions are possible in your program. The program below throws exceptions dependent on the amount of money allocated to a new project:
class NoMoneyException(Exception): pass class OutOfBudget(Exception): pass balance = int(input("Input your balance: ")) if balance < 100: raise NoMoneyException elif balance > 1000000: raise OutOfBudget
It’s a good idea to keep all user-defined exceptions in their file, such as exceptions.py or errors.py. It is also a typical procedure in standard modules.
When an error is detected in the program, Python raises several built-in exceptions if, on the unlikely, the program does not run as unintended. If any of these exceptions occur, the Python interpreter suspends the current process and sends the control to the caller process until the problem is resolved. The program crashes if it is not handled correctly.
Exceptions are handled with the try-except statement. As usual, when you run a program, exceptions may occur. Exceptions are errors that occur during the program’s execution. Python will not notify you of syntax errors (grammar faults) instead of stopping suddenly. Both the end-user and the developer suffer from an abrupt exit. You can use a try-except statement to deal with the problem instead of an emergency halt. You’ll get an emergency halt if you don’t handle exceptions appropriately.