Python 3-Try Except

Python Try Except

The try block, test a block of code for errors.

The except block, handle the error.

The finally block, execute code regardless of the result of the try- and except blocks.

 

Exception Handling

When an error occurs or exception, Python will normally stop and generate an error message.

These errors or exceptions can be handled using the try statements

Example:

The try block will generate an exception, because x is not defined:

try:
    print(x)
except:
    print("An exception occured")

Output:

An exception occurred

When the try block raises an error, the except block will be executed. Without the try block, the program will crash and raise an error.

 

Many Exceptions

We can have many exception blocks as we want, we can have a special block of code for a special kind of error.

Example:

Print one message if the try block raises a NameError and another for other errors:

try:
    print(x)
except NameError:
    print("Variable x is not defined")
except:
    print("Something went wrong")

Output:

Variable x is not defined


Else

We can use else keyword to define a block of code to be executed if no errors were raised.

Example:

In this code, the try block does not generate any error:

try:
    print("Hello!")
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")

Output:

Hello!
Nothing went wrong


Finally

The finally block, will be executed regardless if the try block raises an error or not.

Example:

try:
    print(x)
except:
    print("Something went wrong")
finally:
    print("The try-except is fininshed")

Output:

Something went wrong
The try-except is finished

 

This can be used to close objects and clean up resources

Example:

try:
    f = open("example.txt")
    f.write("Spark Databox")
except:
    print("Something went wrong when writing the file")
finally:
    f.close()

Output:

Something went wrong when writing the file

The above program can also return without closing the file.