codescracker


python

Python Exception Handling



« Previous Tutorial Next Tutorial »


An exception is an event, occurs during the program execution, that disrupts the normal program flow. In case, if a python script raises an exception, then this exception must be handled immediately to continue the program, otherwise it terminates and quiets.

Handle an Exception in Python

If are trying to write some code, than may raise an exception during the program execution, then you can handle the exception just by placing it inside the try block. And after the try block, include an except statement, followed by the block of code that handles the problem as possible. Here is the general form to use try-except-else block in python:

try:
	operation code here;
	...
except Exception1:
	If there is Exception1, then this block is executed
	...
except Exception2:
	If there is Exception2, then this block is executed
	...
else:
	If there is no any exception, then this block is executed

Python Exception Handling Example

Here is an example program, shows how to handle an exception in python program. Let's try to open a file (named nosuchfile.txt), that doesn't exist inside the current directory:

# Python Exceptions - Python Exception Handling - Example Program

try:
    c = open("nosuchfile.txt", 'r')
	print(c.read());
except IOError:
    print("Error in opening the file or the file doesn't exist");
else:
    print("File read successfully..!!");
    c.close()

Since the file nosuchfile.txt is not exist in the current directory. Therefore, there is an exception occurred and handled by the above program. So the output produced by the above python program is:

python exceptions

Now let's try to open a file named myfile.txt created in Python File I/O tutorial. This file exists in the current directory, containing the four line of text. Let's take a look:

# Python Exceptions - Python Exception Handling - Example Program

try:
    c = open("myfile.txt", 'r')
    print(c.read());
except IOError:
    print("Error in opening the file or the file doesn't exist");
else:
    print("File read successfully..!!");
    c.close()

Since, the file myfile.txt exists in the current directory. So here is the output produced by the above python program, prints the content present inside the file:

python exception handling

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test