Python Try Except Finally – Python Programming

Python provides two important options to handle any sudden error in your Python programs and to feature debugging capabilities in them.

The try block enables you to check a block of code for errors.

The except block lets you handle the error.

Python TRY EXCEPT FINALLY
Image by Gerd Altmann from Pixabay

Exception Handling In Python

The finally block enables you to execute code, no matter the results of the try- and except blocks.

When an error, the Python program will stop and generate an error. These errors can be handled using try except Statements

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

We can raise a message using error names. Example – NameError

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

Else in Try Except

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

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

Finally in Try Except

The finally block will be executed no matter what happens to try except block:

try:
print(x)
except NameError:
print("Variable x not defined")
except:
print("Something went wrong!!!")
finally:
print("The try-except is finished")
Try Except Finally Video Tutorial

Whats Next – Python Tutorial For Beginners

Share