Exception Handling in Python
Exception Handling in Python
Software programs and applications do not always work flawlessly. When we write a
program, we can make mistakes that cause errors when we run it. In Python, you may
encounter two types of mistakes: syntax errors and exceptions. Before enabling the rest
of the program to run, you may wish to test a specific block of code to ensure it works
properly. Python try except blocks allow you to test your code and handle exceptions if
they occur. Finally, and else statements can also be used to run additional code based on
the outcome of the try…except block. In this article, we’ll go through how to use the
Python try except concept.
Exception handling is an essential concept in programming that allows developers to
handle errors and exceptions gracefully. Here are the key points related to exception
handling:
1. Types of Errors:
Errors in a program can be categorized into the following types:
Compile Time Error: Occurs during compilation due to syntax issues.
Run Time Error: Occurs while the program is running. Examples include division
by zero, using an undefined variable, or trying to access a non-existing file.
Logical Error: Errors in program logic that lead to incorrect results.
Syntax Errors: Mistakes in code structure that prevent the program from
running.
Semantics Errors: Logic errors that produce unintended results.
2. Exception vs. Error:
An error refers to any mistake or issue in the code.
An exception is an unexpected situation or error during program execution.
3. Exception Handling:
Exception handling involves using try...except blocks to catch and handle
exceptions.
Example (without handling):
Python
num1 = int(input("Enter first number"))
num2 = int(input("Enter Second number"))
result = num1 / num2
print("Result:", result)
.
Example (with handling):
Python
num1 = int (input ("Enter first number"))
num2 = int(input("Enter Second number"))
try:
result = num1 / num2
print ("Result:", result)
except ZeroDivisionError:
print ("You cannot divide a number by zero.")
4. Built-in Exceptions:
Python provides various built-in exceptions that can be caught and handled using
try...except.
Commonly used exceptions include:
SyntaxError: Raised for syntax errors.
IndentationError: Raised for indentation issues.
NameError: Raised when a name is not found.
TypeError: Raised for inappropriate type usage.
Exceptions in Python
An exception is defined as an unexpected condition in a program that causes the
program’s flow to be interrupted.
When the Python interpreter attempts to execute invalid code, it throws an exception,
and if the exception is not handled, it disturbs the regular flow of the program’s
instructions and outputs a traceback. Exceptions are a form of error in which the code
has the correct syntax but contains a fault. There are many different types of exceptions,
but some of the most prevalent are: ArithmeticError, ImportError, ZeroDivisionError,
Name Error, and Type Error.
The try block allows you to check for mistakes in a block of code. The except block
allows you to handle errors with a custom response.
try:
# There can be error code in this block
except:
# Do this to handle exception;
# executed if the try block throws an error
divide (5, 0)
for i in mylist:
try:
print("The entry is", i)
resi = 1/int(i)
break
except:
print('Oops!', sys.exc_info()[0], 'occurred.')
print()
The entry is 0
Oops! <class 'ZeroDivisionError'> occurred.
The entry is 10
The reciprocal of 10 is 0.1
In this program, we loop through the randomList list’s values. As previously stated, the
component that may result in an exception is placed within the try block. If no
exceptions occur, the except block is bypassed and normal flow resumes (for last value).
However, if an exception occurs, it is handled by the except block (first and second
values). Using the exc_info () method from the sys module, we print the name of the
exception. We can see that A results in a ValueError and 0 results in a ZeroDivisionError.
Example
try:
num1 = input('Enter 1st number: ')
num2 = input('Enter 2nd number: ')
result = (int(num1) * int(num2))/ (10 * int(num2))
except ValueError as ve:
print(ve)
exit()
except ZeroDivisionError as zde:
print(zde)
exit()
except TypeError as te:
print(te)
exit()
except:
print('Unexpected Error!')
exit()
print(result)
raise Exception_class,
For example
try:
num = int(input('Enter a positive integer: '))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError('That is a negative number!')
except ValueError as e:
print(e)
Output
try:
# Code
except:
# Executed if error in the try block
else:
# execute if no exception
Example
COPY CODE
def Recp(num):
try:
assert num % 2 == 0
except:
print('Not an even number!')
else:
reciprocal = 1/num
print(reciprocal)
Recp(5)
Recp(10)
Recp(0)
Output
They are less widely utilized because they do not distinguish whether a code has been
successfully performed or not. The syntax followed is mentioned below,
try:
# Code
except:
# Executed if error in the try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example
try:
div = 5/0 # raises ZeroDivisionError exception.
print(div)
finally:
# this block is always executed regardless of exception generation.
print('This is always executed')
Output
The try block allows you to check for mistakes in a block of code. The except block
allows you to handle errors with a custom response.
The Python try except syntax block appears to be as follows:
try:
# There can be error code in this block
except :
# Do this to handle exception;
# executed if the try block throws an error
try:
a = 1/0
except:
pass
finally:
print('Result')
Output
Result
Example
try:
num1 = input('Enter 1st number: ')
num2 = input('Enter 2nd number: ')
result = (int(num1) * int(num2))/(10 * int(num2))
except ValueError as ve:
print(ve)
exit()
except ZeroDivisionError as zde:
print(zde)
exit()
except TypeError as te:
print(te)
exit()
except:
print('Unexpected Error!')
exit()
print(result)
Output
Question 3
What is the use of a raise statement? Write a code to accept two numbers and display
the quotient. Appropriate exception should be raised if the user enters the second
number (denominator) as zero (0).
Answer
The raise statement is used to throw an exception during the execution of a program.
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
if denominator == 0:
raise ZeroDivisionError("Error: Denominator cannot be zero.")
else:
quotient = numerator / denominator
print("Quotient:", quotient)
Output
Enter the numerator: 25
Enter the denominator: 5
Quotient: 5.0
Answer
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
assert denominator != 0, "Error: Denominator cannot be zero."
quotient = numerator / denominator
print("Quotient:", quotient)
Output
Enter the numerator: 12
Enter the denominator: 3
Quotient: 4.0
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1/num2)
print("Both the numbers entered were correct")
except ...............: # to enter only integers
print("Please enter only numbers")
except ...............: # Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great .. you are a good programmer")
...............: # to be executed at the end
print("JOB OVER... GO GET SOME REST")
Answer
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
quotient = (num1 / num2)
print("Both numbers entered were correct")
except ValueError: # 1 : to enter only integers
print("Please enter only numbers")
except ZeroDivisionError: # 2 : Denominator should not be zero
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally: # 3 : to be executed at the end
print("JOB OVER... GO GET SOME REST")
Explanation
When using int(input("Enter the first number")) or int(input("Enter the second
number")), the user is expected to input an integer. If the user enters a non-integer value
(like a string or a floating-point number), a ValueError will be raised during the
conversion to an integer. The except ValueError: block is used to handle this situation by
displaying a message asking the user to enter only numbers.
In the line quotient = (num1 / num2), if num2 is entered as zero, it will lead to a
ZeroDivisionError during the division operation (num1 / num2). The except
ZeroDivisionError: block is used to handle this scenario by displaying a message
informing the user that the second number should not be zero.
The finally: block is used to define code that should be executed regardless of whether
an exception occurs or not.
Question 8
You have learnt how to use math module in Class XI. Write a code where you use the
wrong number of arguments for a method (say sqrt() or pow()). Use the exception
handling process to catch the ValueError exception.
Answer
Note — The TypeError occurs when an incorrect number of arguments is provided for a
function, while the ValueError occurs when the number of arguments are correct but
they contain inappropriate values. Hence, in the following code TypeError is raised due
to providing an incorrect number of arguments to the math.sqrt() and math.pow()
function and it is handled using except.
import math
try:
result = math.pow(2, 3, 4, 5) # pow() expects 2 arguments,
# but 4 are provided
except TypeError:
print("TypeError occurred with math.pow()")
else:
print("Result:", result)
try:
result = math.sqrt(9, 2) # sqrt() expects 1 argument,
# but 2 are provided
except TypeError:
print("TypeError occurred with math.sqrt()")
else:
print("Result:", result)
Output
TypeError occurred with math.pow()
TypeError occurred with math.sqrt()
Question 9
What is the use of finally clause ? Use finally clause in the problem given in Question No.
7.
Answer
The statements inside the finally block are always executed, regardless of whether an
exception has occurred in the try block or not. It is a common practice to use the finally
clause while working with files to ensure that the file object is closed.
print("Learning Exceptions...")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
quotient = (num1 / num2)
print(quotient)
print("Both numbers entered were correct")
except ValueError:
print("Please enter only numbers")
except ZeroDivisionError:
print("Number 2 should not be zero")
else:
print("Great.. you are a good programmer")
finally:
print("JOB OVER... GO GET SOME REST")
Output
Learning Exceptions...
Enter the first number: 12
Enter the second number: 4
3.0
Both numbers entered were correct
Great.. you are a good programmer
JOB OVER... GO GET SOME REST
Learning Exceptions...
Enter the first number: var
Please enter only numbers
JOB OVER... GO GET SOME REST
Learning Exceptions...
Enter the first number: 33
Enter the second number: 0
Number 2 should not be zero
JOB OVER... GO GET SOME REST