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.
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 :-
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 :-
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.
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 2 : www
Please enter number only
Output 2 :- The try blcok getting an ZeroDivisionError exception
Enter no 2 : 0
No 2 should not be zero
Output 3 :- There is no more exception
Enter no 2 : 2
5
Related Links
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 :-
Nothing went wrong
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 :-
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 :-
Without leaving the object file open, the program can continue.
Related Links
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 :-
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 :-
File "demo_ref_keyword_raise2.py", line 4, in < module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed