Python Try Except - Exception Handling


Every program has exception or error. There are two types of exception, which is :

  • Compile Time Error - Its depends on syntax and keyword and you can find out before run program.
  • Runtime Error - Its depends on program login or user input at runtime. The error will generate after run the program.

Exception handling mainly deals with runtime errors. Python provides Try , Except and Finally statements to deal with runtime exceptions.

You can test a code block for errors with the try block.

The block except allows you to deal with the error.

The block finally allows you to execute code irrespective of the result and except blocks.

You can also search for these topics, python try except finally, continue the except try in python, python check the try except any error, assert the try except using python, working of python try except, example for except python try and found, exit the try except in python.

Exception Handling

When a program get an error or exception, then it stop or terminate the program from execution.

Now we write a program without exception handling and see the result:

Example :- This declaration will cause an error because x is not specified :

#This will raise an exception, because x is not defined:

print("Before Error")

# This statement cause an error and program will stop here.
print(x) 

# This statement will not execute because of error.
print("After Error")

Output :-

Before Error

Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in < module>
print(x)
NameError: name 'x' is not defined

The try statement may be used to deal with certain exceptions :

Now try the above program with exception handling and see the result.

Example :- The try block generates an exception, as x is not :

print("Before Error")

try:
  print(x) 
except:
  print("x is not specified")

print("After Error")

Output :-

Before Error
x is not specified
After Error

As the try block causes an error, it is run except block.

The software crash and raise an error without the try block.

You can also search for these topics, python exception handling example, handle the python exception programs, keywords to handle exceptions in python, any errors in python handling of exception, custom functions in python exception handling, define the python to handling the exception code, working of exception handling function using python, define the keyerror for python error handling, python logging into the exception handling.

Many Exceptions

For example, if you wish to run a specific code block on a specific error, you can declare as many exception blocks as possible :

Example :- If the try block raises a ZeroDivisionError and ValueError, depending on the exception occurs :

No1 = 10
print("Enter No 1 : 10")

try:
  No2 = int(input("Enter no 2 : "))
  x = No1/No2
  print(int(x))
except ZeroDivisionError:
  print("No 2 should not be zero")
except ValueError:
  print("Please enter number only")
except:
  print("Something went wrong")
  

Output 1 :- The try blcok getting an ValueError exception

Enter No 1 : 10
Enter no 2 : www
Please enter number only

Output 2 :- The try blcok getting an ZeroDivisionError exception

Enter No 1 : 10
Enter no 2 : 0
No 2 should not be zero

Output 3 :- There is no more exception

Enter No 1 : 10
Enter no 2 : 2
5

You can also search for these topics, python many exceptions defined, use the many python exception keyerror, list the multiple exceptions in python ,found the multiple exceptions in python, raise the python multiple exceptions, how to throw the many exceptions with python.

Else

If you haven't found an error you can use the else keyword to construct a code block to execute :

Example :- The try block generates no error in this example :

#The try block does not raise any errors, so the else block is executed:

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

Output :-

Hello
Nothing went wrong

You can also search for these topics, python else do nothing, python else syntax error, else without if in python, executed the else statement with python, define the block of python else, use the else python condition, working of python else error and empty, how to exit the else in python program, Example for python else.

Finally

If given, the finally block is executed irrespective of whether the try block raises an error.

Example 1 :-

#The finally block gets executed no matter if the try block raises any errors or not:

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

Output :-

Something went wrong
The 'try except' is finished

To close objects and clean up resources this can be useful :

Example 2 :- Try to open and write to an unwritable file :

#The try block will raise an error when trying to write to a read-only file:

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

#The program can continue, without leaving the file object open

Output :-

Something went wrong when writing to the file

Without leaving the object file open, the program can continue.

You can also search for these topics, python finally not executed, finally statement without try in python, python continue the finally, condition to check the finally statement in python, generator mehod in python finally, Example for finally try except using python.

Raise an exception

You can option to make an exception as a Python developer if a condition arises.

Use the raise keyword to throw (or raise) an exception.

Example 1 :- Error raising and stopping if x is below 0 :

x = -1

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

Output :-

Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in < module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

An exception can be raised with the raise keyword.

You can specify the error to raise and the user will be able to print the content.

Example 2 :- Raise TypeError unless x is an integer :

x = "hello"

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

Output :-

Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in < module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed

You can also search for these topics, python raise an exception with a message, how to raise and exit the python exception, custom exception to be raise in python, different threads to raise the python exception, default python to exception raise, Example for python raise an exception.