Python – Try…Except…Finally

Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them.

The try block lets you test a block of code for errors.

The except block lets you handle the error.

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

Exception Handling In Python

When an error, Python program will stop and generate 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 the 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")
Filed under: Python

No comment yet, add your voice below!


Leave a Reply