0% found this document useful (0 votes)
4 views19 pages

Exception Handling in Python

The document provides a comprehensive overview of exception handling in Python, detailing the types of errors, the use of try-except blocks, and how to catch and raise exceptions. It explains the significance of handling exceptions gracefully to prevent program crashes and includes examples of various exception handling techniques. Additionally, it covers the use of else and finally clauses, as well as common queries related to exception handling.

Uploaded by

kainatsjs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Exception Handling in Python

The document provides a comprehensive overview of exception handling in Python, detailing the types of errors, the use of try-except blocks, and how to catch and raise exceptions. It explains the significance of handling exceptions gracefully to prevent program crashes and includes examples of various exception handling techniques. Additionally, it covers the use of else and finally clauses, as well as common queries related to exception handling.

Uploaded by

kainatsjs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

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.

As Python developers, we must consider various exception circumstances and


incorporate error management into your code. Python, fortunately, includes a
sophisticated error handling system. Python applications may determine the error type
at run time and act accordingly by using structured exception handling and a collection
of pre-defined exceptions. These actions can include adopting a different route, using
default settings, or urging for accurate input.

Catching Exceptions in Python


For exception handling, most current programming languages employ a mechanism
known as “try-catch.” Exceptions in Python can be managed with a try statement. This
prevents the program from exiting abruptly in the event of an error. The basic form in
Python is the “Python try except.” The try clause contains the critical operation that can
cause an exception. The except clause contains the code that handles exceptions.

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 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

So how exactly does the Python try except clause works?


The try clause is run first, followed by the code between the try and except clauses.
If there is no exception, only the try clause will be executed, unless the clause is
completed.
And if an exception occurs, the try clause is bypassed and the except clause is executed.
If an exception occurs but the except clause within the code does not handle it, the
exception is passed on to the outer try statements. If the exception is not handled, the
execution is terminated.
There can be more than one unless a clause in a try statement.
Let us look at a basic try-except clause program below,

def divide (x, y):


try:
res = x / y
print ('Your answer is :', res)
except ZeroDivisionError:
print ('Sorry! You are dividing by zero')

divide (5, 0)

Sorry! You are dividing by zero

Another example is as follows,

# import module sys to get the type of exception


import sys
mylist = ['A', 0, 10]

for i in mylist:
try:
print("The entry is", i)
resi = 1/int(i)
break
except:
print('Oops!', sys.exc_info()[0], 'occurred.')
print()

print('The reciprocal of', i, 'is', resi)


Output
The entry is A
Oops! <class 'ValueError'> occurred.

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.

Catching Specific Exceptions in Python


In the previous example, no specific exception was mentioned in the unless clause. This
is a bad programming technique because it will catch all exceptions and treat every case
the same way. We can indicate which exceptions should be caught with an except clause.
To trap distinct types of exceptions, you can include numerous “except” blocks in the
“try” block. This is beneficial because each “except” block will handle a different type of
error.

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)

Enter 1st number: 10


Enter 2nd number: 0
division by zero

Enter 1st number: One


Enter 2nd number: Ten
invalid literal for int() with base 10: 'One'

Enter 1st number: 20


Enter 2nd number: 10
2.0

Raising Exceptions in Python


Exceptions are raised in Python programming when faults occur during runtime. The
raise clause in Python can be used to forcefully raise an exception. It comes in handy
when we need to throw an exception to stop the application from running. We can
optionally pass values to the exception to explain why it was raised. The syntax for using
the raise statement is as follows.

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

Enter a positive integer: -10


That is a negative number!

Python try with else clause


In some cases, you may want to run a specific bit of code if the code block inside try
completed without errors. You can utilize the optional else keyword with the try
statement in these circumstances. You can also use the else clause on the try-except
block in Python, which must come after all the except clauses. If there are no exceptions
thrown by the “try” block, the “else” block is executed. The syntax is as follows,

try:
# Code
except:
# Executed if error in the try block
else:
# execute if no exception

Note – If and only if no exception is triggered, the else clause is executed.

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

Not an even number!


0.1
Traceback (most recent call last):
File "", line 12, in
File "", line 7, in Recp
ZeroDivisionError: division by zero
Python try…finally
But what if we want a message to be printed if an error is returned as well as if no error
is found? In Python, the try statement can include an optional finally clause. This clause
is always executed and is typically used to release external resources. The final block is
always run after the try block has terminated normally or after the try block has
terminated owing to specific exceptions.

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)

# handles ZeroDivision exception


except ZeroDivisionError:
print('Cannot divide by Zero')

finally:
# this block is always executed regardless of exception generation.
print('This is always executed')
Output

Cannot divide by Zero


This is always executed

SOME COMMON QUERIES

Q1. What is try except in Python?


For exception handling, most current programming languages employ a mechanism
known as “try-catch.” Exceptions in Python can be managed with a try statement. This
prevents the program from exiting abruptly in the event of an error. The basic form in
Python is the “Python try except.” The try clause contains the critical operation that can
cause an exception. The except clause contains the code that handles exceptions.

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

Q2. Can I use try without except in Python?


We can’t have a try block without an except block, so the only thing we can do is try to
ignore the thrown exception so that the code doesn’t move to the except block and
define the pass statement in the except block, as seen before. The pass statement is the
same as writing an empty line of code. Finally, we can use the block. Regardless of
whether an exception happens or not, code will be executed.
Example

try:
a = 1/0
except:
pass
finally:
print('Result')

Output
Result

Q3. In Python can a try have multiple except?


We can indicate which exceptions should be caught with an except clause. To trap
distinct types of exceptions, you can include numerous “except” blocks in the “try” block.
This is beneficial because each “except” block will handle a different type of error.

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

Enter 1st number: 10


Enter 2nd number: 0
division by zero

Enter 1st number: One


Enter 2nd number: Ten
invalid literal for int() with base 10: 'One'

Enter 1st number: 20


Enter 2nd number: 10
2.0

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

Enter the numerator: 2


Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 4, in <module>
raise ZeroDivisionError("Error: Denominator cannot be zero.")
ZeroDivisionError: Error: Denominator cannot be zero.
Question 4
Use assert statement in Question No. 3 to test the division expression in the program.

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

Enter the numerator: 5


Enter the denominator: 0
Traceback (most recent call last):
File "c:\PythonPlayground\q3.py", line 3, in <module>
assert denominator != 0, "Error: Denominator cannot be zero."
AssertionError: Error: Denominator cannot be zero.
Question 5
Define the following:
Exception Handling
Throwing an exception
Catching an exception
Answer

Exception Handling — The process of writing additional code in a program to give


proper messages or instructions to the user upon encountering an exception is known
as exception handling.
Throwing an exception — Throwing an exception refers to the process of creating an
exception object and passing it to the runtime system or the appropriate exception
handler.
Catching an exception — Catching an exception refers to the process of executing a
suitable handler or block of code specifically designed to handle that particular
exception when it occurs during program execution.
Question 6
Explain catching exceptions using try and except block.
Answer
An exception is said to be caught when a code that is designed to handle a particular
exception is executed. Exceptions, if any, are caught in the try block and handled in the
except block. While writing or debugging a program, a user might doubt an exception to
occur in a particular part of the code. Such suspicious lines of codes are put inside a try
block. Every try block is followed by an except block. The appropriate code to handle
each of the possible exceptions (in the code inside the try block) are written inside the
except clause. While executing the program, if an exception is encountered, further
execution of the code inside the try block is stopped and the control is transferred to the
except block. The syntax of try … except clause is as follows:
try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is encountered]
Question 7
Consider the code given below and fill in the blanks.

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

You might also like