Python Exception Handling

Python Exception Handling:

When an error or exception occur that time Python will normally stop and generate an error message and stop the program from getting terminate.

This is known as exception handling.

The keywords use for exception handling are:-

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

2. except block lets you handle the error.

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


try and except statement:

Exceptions can be handled using the try statement.

Example:

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

Output:
An exception occurred

Since the try block raises an error as x is not defined, the except block will be executed, without try statement the program will crash.


finally statement:

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

Example:

try:
  print(x)
except:
  print("A great error")
finally:
  print("This will executed")

Output:
A great error
This will executed

# The finally block will get executed regardless try block execute or not.


try block with else statement.

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

Example:

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

Output:
Hello Python
Nothing went wrong

Post a Comment

0 Comments