Python Try Except for Exception Handling

Master exception handling in Python using the try, except, else, and finally blocks. Learn how to test, catch, and manage errors effectively to ensure smooth execution of your Python code.



Python Try Except

The try block allows you to test a block of code for errors. The except block enables you to handle the error. The else block lets you execute code when there is no error, and the finally block lets you execute code regardless of the result of the try-except blocks.

Exception Handling

When an error occurs, or an exception, Python usually stops and generates an error message. These exceptions can be handled using the try statement:

Example

try:
    print(y)
except:
    print("An exception occurred")
Output

An exception occurred

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

Example

print(y)

Handling Multiple Exceptions

You can define as many exception blocks as you want, for example, if you want to execute a special block of code for a specific kind of error:

Example

try:
    print(y)
except NameError:
    print("Variable y is not defined")
except:
    print("Something else went wrong")
Output

Variable y is not defined

Using the Else Keyword

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example

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

Hello
Nothing went wrong

Using the Finally Keyword

The finally block, if specified, will be executed regardless of whether the try block raises an error or not:

Example

try:
    print(y)
except:
    print("Something went wrong")
finally:
    print("The 'try except' is finished")
Output

Something went wrong
The 'try except' is finished

This can be useful for closing objects and cleaning up resources:

Example

try:
    f = open("demofile.txt")
    try:
        f.write("Lorem Ipsum")
    except:
        print("Something went wrong when writing to the file")
    finally:
        f.close()
except:
    print("Something went wrong when opening the file")
Output

Something went wrong when opening the file

Raising Exceptions

As a Python developer, you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword:

Example

x = -5

if x < 0:
    raise Exception("Sorry, no numbers below zero")
Output

Traceback (most recent call last):
  File "example.py", line 3, in 
    raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

You can define the type of error to raise, and the text to print to the user:

Example

y = "world"

if not type(y) is int:
    raise TypeError("Only integers are allowed")
Output

Traceback (most recent call last):
  File "example.py", line 3, in 
    raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed