Python Exception Handling

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. This could be a programming error attempting to divide by zero , attempting to invoke a method on an object that does not define the method, or passing an invalid argument to a method. When an exception occurs program execution gets terminated. In such cases we get a system generated error message .

Why an exception occurs?

There can be several reasons that can cause a program to throw exception . For example, when we try to read a file or get input from a user, there is a chance that something unexpected will happen – the file may have been moved or deleted, and the user may enter data which is not in the right format.

Python Exception Handling

The good thing about exceptions is that they can be handled in Python . By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user. All the runtime errors that we have encountered are called exceptions in Python. Python uses them to indicate that something exceptional has occurred, and the program cannot continue unless it is handled.

All exceptions are subclasses of the Exception class. A try-except statement can be used to wrap entire programs or just particular portions of code to trap and identify errors. If an error occurs within the try statement, an exception is raised, and the code under the except statement is executed. For example, it is not possible to divide by zero . If we try to do this, a ZeroDivisionError is raised and the script is interrupted.

example
value = 10 zero = 0 result = value/zero print(result)

The following error message will get when the above code is executed.

Traceback (most recent call last): File "test.py", line 5, in < module > result = value/zero ZeroDivisionError: division by zero

A try-except statement can be used to wrap entire programs or just particular portions of code to trap and identify errors. Place the code where we expect an exception after try keyword. The except keyword catches the exception if it is raised. The exception type is specified after the except keyword.

example
value = 10 zero = 0 try: result = value/zero except ZeroDivisionError: print("Divided by zero is not possible")
output
Divided by zero is not possible

try...finally

A finally clause is always executed before leaving the try statement , whether an exception has occurred or not. Suppose you are reading a file in your Python program. How do you ensure that the file object is closed properly whether or not an exception was raised? This can be done using the finally block . The finally clause can use to make sure files or resources are closed or released regardless of whether an exception occurs, even if you don't catch the exception.

example
try: myfile = open("test.txt", "w") # perform file operations finally: myfile.close()

This type of construct makes sure the file is closed even if an exception occurs.