Python Exception Handling

In this tutorial you will learn about Python exception handling, try, catch and finally block.

Program code is developed by humans and therefore it is about to be wrong sometimes. It may happen that our code consists of errors such as run-time error, syntax error, semantic errors and many others. It is important for Python to block the execution of a program and raise error messages. This is what is known as exceptions.

Python Exception Handling

An exception is an undesirable event which arises during the execution of a program that disrupts the normal flow of the program’s instructions.

To handle these errors or exceptions, we use the technique of Exception Handling.

Exceptions are normally caused due to the following events:

1. A File that is to be opened but is not found in the memory.
2. Invalid entry of data by the user.

Example

Python Exception Handling

This is an example of Python error. The benefit with Python is that it provides us well details error messages.

In the above program, it tells me the error line number and the error line code. Morever, it also tells me if I have forgotten anything. Like, in the above program I have missed to declare variable a and directly printing variable onto the console.

With the help of Python exception handling technique, we can avoid abrupt termination of a program and handle interruptions and errors and prevent the program from closing abruptly.

While making your program code, if you think that a certain part of your program code may not work properly, then on execution it may terminate abruptly and your system may crash. To prevent all of this, you may add an exception block in your code so that if an error occurs, Python Interpreter will catch that exception and prevent your program from crashing.

Check out fixexception.com to find fixes for exceptions in Python.

Python Standard Exceptions

There are some pre-defined or standard exceptions in the Python library. So, you can use one of them if your needs are sufficed. These exceptions are as follow:

IOError: It is raised when an I/O operation fails to execute such as when an attempt is made to open a file in read mode that does not exist.

IndexError: This error is raised when a sequence is indexed with a number of an element that does not exist.

KeyError: This error is raised when a dictionary key is not found.

NameError: It is raised when a name of an identifier such as a variable or a function is not found.

SyntaxError: It is raised when a syntax error occurs.

TypeError: It is raised when a built-in operation or function is applied to an object of inappropriate datatype.

ValueError: It occurs when a built-in operation or a function receives an argument that has the right type but an inappropriate value.

ZeroDivisionError: It is raised when the second argument of a division or modulo operation is zero.

Python try except Block

The standard way to handle exceptions is by including a try and except block in your program code. In the try block, you can write a section of code that could probably raise an error. The except block is then written so that if your exception comes true, the control of the program will be passed to the except block and you could thus prevent program from abnormal termination.

Syntax

try:
	statement 1
	statement 2
	statement n
except:
	statement 1
	statement 2
	statement n

Example

try:
	var1=float(raw_input("Enter a Number:\n"))
	print("\n")
except:
	print("Erorr Executing")

Output

Python Exception Handling

Here, I have declared a variable to take in float value through raw_input() function. I have included this code into try block so that if an error occurs I could transfer it into exception block and can then handle the program by giving an error message.

I have entered string value “thecrazyprogrammer.com” whereas the interpreter expects me to enter a float value, this arises an exception. On exception, the control is transferred to the except block and the print statement is executed.

Multiple Exception Block

You can also include multiple exception blocks with single try block which helps the Python interpreter to specify exactly what the error is.

Example

try:
	var1=float(raw_input("Enter a Number:\n"))
	print("\n")
except(SyntaxError):
	print("Syntax Error Occured\n")
except(TypeError):
	print("Invalid Datatype")
except(ValueError):
	print("Invalid Value")

Output

Python Exception Handling

Here, I have entered an invalid value as “thecrazyprogrammer.com” which is wrong as the program expects a float value and hence the control is transferred to the correct exception block which is ValueError.

Python finally Block

A finally block is very useful in Python exception handling. A finally clause always gets executed as soon the control completes the try block. It doesn’t matter whether an exception has occurred or not.

Syntax

finally():
	statement 1
	statement n

Example

try:
    var1=float(raw_input("Enter a Number:\n"))
    print("\n")
except:
    print("Erorr Executing\n")
finally:
	print("We are in finally block")

Output

Python Exception Handling 4

In the above example, the prompt asks the user to enter an integer. After an integer is entered, it checks in for exception and since the input is correct it directly goes to the finally block.

Again we try to run the same program and now enter a wrong input i.e., string. This time an exception has been occurred and now the control will go to the exception block and as soon as the exception block execution gets over, the control will move into finally block and then terminate or go to the next sequence of statements whichever occurs first.

If you find anything incorrect or have any doubts regarding above Python exception handling tutorial then please comment below.

Leave a Comment

Your email address will not be published. Required fields are marked *