Pyton

Python Exception

Python Exception

An exception is an event that arises during the execution of a program to terminate or change the normal flow of a program. An error, for example, raises an exception. Like other programming languages, Python contains many built-in exceptions. These exceptions are raised if an error is encountered when the program is executed. The type of error determines which exception is to be raised. When an exception occurs, the Python interpreter checks whether the exception is handled; if not, it terminates the program. This article explains exceptions in Python through various examples.

Built-in Python Exceptions

As discussed earlier, Python has many built-in exceptions that are raised when an error occurs during the execution of a program. Every exception is derived from an “Exception” base class. The following include some built-in Python exceptions, along with a short description of each exception type:

Exception Description
Exception Every exception is derived from this class.
ImportError This exception is raised when a specific module is imported, and it is not found.
EOFError This is the end-of-file exception. This exception occurs when the end of the file is reached.
ZeroDivisionError This exception is raised when a number is divided by zero.
KeyError This exception is raised if a certain key that is not defined inside a dictionary is specified or used.
IndexError This exception is raised when access to an index of sequence that is not in the range has been attempted.
FloatingPointError This exception is raised when a floating-point operation is failed.

These are some of the built-in exceptions in Python. Please visit the official documentation for more information about using built-in exceptions in Python, located at https://docs.python.org/3/library/exceptions.html.

Exception Usage in Python

Exceptions in Python are handled using the try statement. The piece of code that can throw or raise an exception is implemented in a try block. Next to the try block, an except block is implemented to handle the exception. In the except block, we catch the exception and decide what operation to perform when we encounter that particular exception. The syntax of writing the try and except blocks is as follows:

try:
perform the operation or function
except:
functionality to handle the exception

Now, we will implement a simple code in our Python script using the try and except blocks.

Here, we will print a 'name' variable that is not defined. This raises an exception in the except block.

#implementing the try block
try:
print(name)
#implementing the except block
except:
print("An exception occurred")

Output

If no exception occurs, then only the try block is executed. In the except block, a statement is printed that an exception has occurred.

Let us look at another example where we define the name variable:

#defining the name variable
name = "Mark"
#implementing the try block
try:
print(name)
#implementing the except block
except:
print("An exception occurred")

Output

In the above example, the try block is executed and the except block is skipped because the program does not raise any exceptions. We can define as many except blocks in our program as we want. Every except block handles a specific kind of exception.

#implementing the try block
try:
print(name)
#implementing the except block to catch the name error
except NameError:
print("The variable is not defined")
#implementing the except block
except:
print("Something went wrong other than name error")

Output

In Python, Exception is the base class for all exceptions. Instead of writing the name of a particular exception in the except block, we can simply write “Exception” and catch every type of exception in this way.

#implementing the try block
try:
print(name)
#implementing the except block to catch the error
except Exception as exp:
print(exp.__class__)
#implementing the except block
except:
print("Something went wrong other than name error")

Output

The exp.__class__ returns the name of the class of exception.

Similarly, let us look at an example of the “ZeroDivisionError” class.

#implementing the try block
try:
x=1/0
print(x)
#implementing the except block to catch the error
except Exception as exp:
print(exp.__class__)
#implementing the except block
except:
print("Something went wrong other than name error")

Output

The else Block

The else block is used with the try and exception blocks. The else block defines a piece of code that is executed if the try block executes successfully and no error occurs. Sometimes, you may need to print a message or perform a function when the try block has been successfully executed. For this reason, we can implement the else block with the try and except blocks.

In this example, we will implement the else block in our Python script.

#implementing the try block
try:
x=1/2
print(x)
#implementing the except block to catch the error
except Exception as exp:
print(exp.__class__)
#implementing the else block
else:
print("Everything went fine")

Output

The else block is executed following the successful execution of the try block.

Let us now look at another example using the else block.

#implementing the try block
try:
name="Mark"
#implementing the except block to catch the error
except Exception as exp:
print(exp.__class__)
#implementing the else block
else:
print("The name is: ",name)

Output

In the above example, the name variable is defined inside the try block and is printed in the else block.

The finally Block

The finally block contains the piece of code that must be executed regardless of whether the try block raises an exception. The finally block is optional and is declared with the try block. For instance, if we have opened a text file to read the try block and it raises an error or exception, it is better to enclose the file in the finally block, even if the error occurs. Let us implement the finally block in our Python script.

#implementing the try block
try:
print(my_dict)
#implementing the except block to catch the error
except Exception as exp:
print(exp.__class__)
#implementing the finally block
finally:
print("This is the finally block")
print("The finally block is executed")

Output

In the output, it can be seen that the try block raises an exception. However, the finally block is executed at the end.

Now, let us open a text file in the try block, which raises an exception while the file enclosed in the finally block.

#implementing the try block
try:
fileObj=open("mystudent.xml","r")
fileObj.seek(-2)
print(fileObj.readlines())
#implementing the except block
except Exception as exp:
print(exp.__class__)
#implementing the finally block
finally:
fileObj.close()
print("File is successfully closed")

Output

As you can see, regardless of the value error, the file has been closed successfully inside the finally block.

Raise an Exception

Although exceptions are raised automatically when an error occurs, in Python, you can also raise exceptions manually. The raise keyword is used to raise or throw the exception.

We will now raise some exceptions using the raise keyword. In the following example, the if condition is implemented to check for non-negative numbers. If any non-negative numbers exist, then the exception “Non-negative numbers are not allowed” is raised.

#declaring two number variables
num1 = 20
num2= -10
if ((num1<0) | (num2<0)):
raise Exception("Non-negative numbers are not allowed")
else:
print(num1+num2)

Output

Conclusion

An exception occurs in response to an error at run time. In Python, we can handle exceptions by using the try and except blocks. This article explained how to use exceptions in Python through various examples.

Gry Battle for Wesnoth Tutorial
Battle for Wesnoth Tutorial
The Battle for Wesnoth is one of the most popular open source strategy games that you can play at this time. Not only has this game been in developmen...
Gry 0 A.D. Tutorial
0 A.D. Tutorial
Out of the many strategy games out there, 0 A.D. manages to stand out as a comprehensive title and a very deep, tactical game despite being open sourc...
Gry Unity3D Tutorial
Unity3D Tutorial
Introduction to Unity 3D Unity 3D is a powerful game development engine. It is cross platform that is it allows you to create games for mobile, web, d...