Exception Handling
Exception Handling
An error is an action that is incorrect or inaccurate. For example, syntax error. Due to which the
program fails to execute.
The errors can be broadly classified into three types:
1. Syntax errors
2. Logical errors
3. Runtime errors
1. Syntax Error- The syntax errors occur when the code violates the rules of the python
language syntax. These errors are detected by the python interpreter when it is parsing the code.
A syntax error is also known as a parsing error.
When Python parses the program and finds an incorrect statement it is known as a syntax error.
When the parser found a syntax error it exits with an error message without running anything.
Common Python Syntax errors:
• Incorrect indentation
• Missing colon, comma
• Unmatched parenthesis and missing quotes
• Using a keyword as a variable name
Example-
print("Welcome to Python")
print("Learn Python with us..")
Output-
print("Learn Python with us..")
^
IndentationError: unexpected indent
2. Logical Error- Logical error when the code is syntactically correct and runs without causing
any errors, but the output is not what you expected. These errors can be cause by incorrect
algorithmic design, mathematical errors or a misunderstanding of the problem requirements.
Example-
a=5
b=10
average=a+b/2
print(average)
3. Runtime Error- Runtime errors occur when the code is syntactically correct but causes an
error when it is executed. These errors can be causes by a variety of reasons, such as invalid
input data, division by zero, or accessing an undefined variable.
Example-
list1= [10,20,30]
Print(list1[4])
Output- Index error
Exceptions in Python Programming- Errors that occur at runtime (after passing the syntax test)
are called exceptions. Exceptions can be caught and handled by the programmer.
The exceptions can be broadly classified into two types:
1. Build-in Exception
2. User define Exception
3. ValueError- Raised when a function gets an argument of correct type but improper value.
8. ZeroDivisionError- Raised when the second operand of division or modulo operation is zero.
we learned about Python exceptions. We know that exceptions abnormally terminate the execution of a
program. Since exceptions abnormally terminate the execution of a program, it is important to handle
Python try...except Block- The try...except block is used to handle exceptions in Python. Here's the
Syntax try:
except:
When an exception occurs, it is caught by the except block. The except block cannot be used without
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print ("Error: Denominator cannot be 0.")
In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, result = numerator/denominator inside the try block.
Now when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block are executed.
If none of the statements in the try block generates an exception, the except block is skipped.
For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle
each exception differently.
The argument type of each except block indicates the type of exception that can be handled by it.
For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print ("Denominator cannot be 0.")
except IndexError:
print ("Index Out of Bound.")
In some situations, we might want to run a certain block of code if the code block inside try runs without
any errors.
For these cases, you can use the optional else keyword with the try statement.
For example:
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
Output
If we pass an odd number:
Enter a number: 1
Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4
0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else is not handled by
preceding except.
Python try...finally-
In Python, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
For example, -
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
Output
Error: Denominator cannot be 0.
This is finally block.
In the above example, we are dividing a number by 0 inside the try block. Here, this code generates an
exception.
The exception is caught by the except block. And, then the finally block is executed.
2. User define Exceptions-
User defined exceptions in python are created by programmers to enforce constraints on the values
which the variables in the program can take. User defined exceptions can be implemented by raising an
exception explicitly.
Using raise keyword explicitly after conditional statements-
Inbuilt exceptions are raised automatically by a program in python but we can also raise inbuilt
exceptions using the python try except blocks and raise keyword. By raising an inbuilt exception
explicitly using raise keyword, we can use them anywhere in the program to enforce constraints on the
values of variables.
For example,
suppose we have to calculate the year of birth of a person from its age, we can do it as following:
age= 10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
Output-
Age is:
10
Year of Birth is:
2011
The program has given proper output in the case by subtracting age from current year. Now suppose we
give a negative value for age in input, say -10.
age= -10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
Output-
Age is:
-10
Year of Birth is:
2031
When we provide a negative number for age, the program still works fine but gives an output
which is logically incorrect because no person can have his year of birth in future.
To prevent this kind of year, we can check if the value given in age as input is negative and then
we can force the program to raise an exception using raise keyword as follows.
The syntax for raise statement is raise ExceptionName . When an error is raised, the code in the except
block should handle the exception otherwise it will cause error in the program.
try:
age= -10
print("Age is:")
print(age)
if age<0:
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except ValueError:
print("Input Correct age.")
Output-
Age is:
-10
Input Correct age.
Here we can see that for age -10, the program handles the case successfully. Lets check if it gives correct
year of birth when given correct value of age.
try:
age= 10
print("Age is:")
print(age)
if age<0:
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except ValueError:
print("Input Correct age.")
Output-
Age is:
10
Year of Birth is:
2011