Python Exception Handling

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

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement:

Example

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

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

Since 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

This statement will raise an error, because x is not defined:

 
print(x)

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute 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 else went 
  wrong")

Else

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

Example

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

Python Exception Handling

We have explored basic python till now from Set 1 to 4 (Set 1 | Set 2 | Set 3 | Set 4). 

In this article, we will discuss how to handle exceptions in Python using try. catch, and finally statement with the help of proper examples. 

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. 

Difference between Syntax Error and Exceptions

Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the termination of the program. 

Example: 

 # initialize the amount variable
amount =10000
 
# check that You are eligible to
#  purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

Output:

Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an error. This error does not stop the execution of the program, however, it changes the normal flow of the program.

Example:

 # initialize the amount variable
marks =10000
 
# perform division with 0
a =marks /0
print(a)

For more, checkout W3Schools and Geeks For Geeks.