To be a good programmer, you must know how to handle exceptions. Python provide two features to help you handle exceptions. They are:
- Exception Handling
We would cover the following topics
- What are Exceptions
- Handling Exceptions
- Some Rules about try Statement
- The except Clause without Exceptions
- The Except Clause with Multiple Exceptions
- The try…finally Clause
- Parameters to Exceptions
- Raising an Exception
- User-Defined Exception
1. What are Exceptions?
An exception in Python is an event that occurs during the execution of a program that alters the normal flow of the program sequence.
Generally, when a Python program encounters such a situation, it raises an exception. An exception is an object in Python that represents an error.
When an exception is raised, then it must be handled immediately. If not handled, the program would terminate and quit.
2. Handling Exception
Normally there a codes that have high likelihood of causing exceptions. For such code, you must place them inside a try: block.
The try block is followed by an except: statement. Then followed by a block of code that would run if an exception should occur.
The syntax for handling exception is given below:
try: code that may cause exception here ... except Exception1: code to run if Exception1 occurs ... except Exception1: code to run if Exception2 occurs ... else: code to run if there is no exception
3 Some Rules for try Statement
– A single try block can have more than one except statements. This is necessary where different types of exceptions can be thrown.
– You can also provide a common except statement, that can handle different types of exceptions
– After the except block, you can optionally include an else clause. The code in the else block executes whether exception occurs or not
For example, see the code below:
# code to handle IOError try: myfile = open("D:/data/file.txt", "w+") myfile.write("Hello World") except IOError: print("Error occurred: cannot access file") else: print("Data has been written to file") myfile.close()
4. The except Clause without Exceptions
You can also use the except clause without exception. In this case, you except block would handle any type of exception that occurs.
An example is given below:
# handle any type of exception try: code that may cause exception here ... except: code to run if Exception1 occurs ... else: code to run if there is no exception
In case of the code above, you can see that no Exception type is provided. So this would then catch whatever exception that occurs. I would recommend you don’t handle exceptions this way.
The reason is because it does not provide you a way to identify the actual cause of the problem
5. The except Clause with Multiple Exceptions
Let’s now look at a situation where we can include multiple exceptions in the same line. For example, take a look at the code below.
# code to handle multiple exceptions try: code that may cause exception ... except(Exception1[, Exception2[,...ExceptionN]]]): code to execute if any of the listed exceptions occur ... else: code to execute if exception does not occur ...
6. The try-finally Clause
Python provides yet another block that you can use. That is the finally: block. In the finally block, you place any code that must execute whether exception occurs or not.
The syntax for this is given below:
# the finally block try: code that may cause exception ... except(Exception1[, Exception2[,...ExceptionN]]]): code to execute if any of the listed exceptions occur ... finally: code to execute whether exception occurs or not ...
Also note that you cannot use the finally block along with the else block
7. Parameters of Exception
An exception can accept an argument. The argument specifies value of additional information about the problem that occurred.
The argument depends on the type of exception. For example
# argument to exception try: code that may cause exception ... except ExceptionType, Argument: you can examine the value of the argument ...
If you code handles a single exception, then the argument variable follows the name of the exception, as in the code above. But if you are handling multiple exceptions, then the argument variable would follow the tuple of the exception.
8. Raising Exceptions
You can actually create an exception! You do this using the raise: statement. The syntax is given below:
raise [Exception [, args [, traceback]]]
In the code:
- Exception is the type of exception.
- args is the argument variable
- traceback is the traceback object (seldom used)
If you raise and exception, then the code following the raise statement is not executed. For example
def functionName( entry ): if level < 1: raise "Incorrect entry", entry # The code below to this would not be executed # since we raised an exception
9. User-Defined Exceptions
In Python, you can create your own exceptions. You do this by deriving from the standard built-in exception classes.
For example, assuming we want to create an exception that derives from RuntimeError. So we create class that derives from RuntimeError. Let’s call this class NetworkError.
For example, you can see the code below
# User-defined exceptions class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
So, once we have this class, then we can use it. You use by raising an exception with it. This is shown in the code below:
# Raising a User-defined error try: raise Networkerror("Invalid address") except Networkerror,e: print e.args