0% found this document useful (0 votes)
3 views22 pages

Exception Handling in Python-Notes (1)

The document provides an overview of exception handling in Python, detailing various types of errors such as syntax, logical, and runtime errors. It explains the mechanisms for handling exceptions, including the use of try, except, else, and finally blocks, along with examples of each method. Additionally, it emphasizes the importance of managing exceptions to prevent abnormal program termination and data loss.

Uploaded by

kashisajitv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views22 pages

Exception Handling in Python-Notes (1)

The document provides an overview of exception handling in Python, detailing various types of errors such as syntax, logical, and runtime errors. It explains the mechanisms for handling exceptions, including the use of try, except, else, and finally blocks, along with examples of each method. Additionally, it emphasizes the importance of managing exceptions to prevent abnormal program termination and data loss.

Uploaded by

kashisajitv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 22

EXCEPTION HANDLING IN PYTHON

INTRODUCTION
• In Python, during the execution of program, sometimes the program does not execute at all or
generates an unexpected output.
• This is due to the problem that the program code may contain Syntax error or Run time error or
Logical error.
Types of Errors:
Syntax Errors:
• Syntax is a set of rules that a program must follow to compile correctly.
• Syntax errors occurs when we violate any grammatical rules of the programming language.
• Examples:
Missing parenthesis, punctuation inserted wrong place etc…
Logical Errors:
• A logical error/bug (called semantic error) does not stop execution but the program behaves incorrectly
and produces undesired/wrong output.
• Examples:
• wrong variable name for calculations, Using integer division or modulus operator in place of division
operator
Runtime error
• Runtime error happens when a program instructs a computer to carry out a task that it
either cannot do or is too slow to perform.
• This error causes the abnormal program termination during execution.
Types of Runtime Errors:
• Name Error: It occurs when a non existent variables are used in the program.
Example: >>>print(x)
Name Error: name ‘x’ is not defined
• Type Error: It occurs when an incorrect datatype is supplied in the program.
Example: Indexing a string, list or tuple with something other than integer, passing wrong
number of arguments to a function etc…
• Value Error: It occurs when inappropriate value is used in a program.
Example: >>>x=int(input(“Enter a Number:”))
Enter a Number: apple
Value Error: invalid literal for int() with base 10: ‘apple’
• Index Error: It occurs when we access the index of a sequence out of its range.
Example: >>>a=[10,30,50]
>>> print(a[5])
IndexError : list index out of range
• Indentation Error: It occurs when the rule for indentation is broken.
• EOFError: This occurs when there is no record or data to read from a file.i.e., methods in files tries to
read beyond the file.
• KeyError: This type of error occurs when we access a key which does not exist in a dictionary.
Example: >>>dict={‘January’:31, ‘February’:28, ‘March’:31}
>>>dict[‘April’]
KeyError: ‘April’
• ZeroDivisionError: This occurs when a division expression has zero as denominator.
Example: >>>print(55/0)
ZeroDivisionErro: division by zero
• IOError: This exception occurs whenever there is an error related to input/output such
as opening a file that does not exist, trying to delete a file in use, removing USB while
read/ write operation is going on.
• In all these situations, where some interrupt occurs in input/ output operation, IOError
exception is raised
EXCEPTIONS
• If any error occurs during the execution of program, an abnormal
termination in the program occurs and it may cause loss of data or
software problem or system crash.
• The error that arises during the execution of a program is called an
Exception.
• Such exceptions need to be handled by the programmer so that
program does not terminate abnormally.
• Commonly occurring exceptions are defined in the compiler and called
built-in exceptions.
• Python standard library provides solution for handling such built-in
exceptions.
EXCEPTION HANDLING
• Python provides some mechanisms to handle the errors that occur during the execution of
program and it is called Exception Handling.
Terms related to Exception Handling are:
Traceback:
• The lengthy error message that is shown when an exception occurs during
the program run is called a traceback.
• The traceback gives information regarding the line number(s) along with the function calls
that caused the exception.
Try block:
• Try block constitutes a set of codes that might have an exception thrown in it. If any code
within the try statement causes an error, execution of the code will stop and jump to the
except statement.
‘except’ block or ‘catch’ block:
• Whenever some error or exception is to be handled, it is done using ‘except’ block which
stands for exception.
‘throw’ or ‘raise’ block:
• When an exception occurs in the program, we say that exception was raised or thrown.
• Next, we deal with it and say it is handled or caught. And the code written to handle it is
known as exception handler.
• ‘throw’ is an action in response to an exception (error/unusual condition).
• When a program on execution encounters an abnormal condition, an object of this
exception is created or instantiated and ‘thrown’ or ‘raised’ to the code responsible to
catch/handle it.
Unhandled, uncaught Exception:
• An exception that leads to abnormal termination of a program due to non-execution of an
exception thrown is termed as unhandled or uncaught exception.
• This is the result of an exception which was thrown or raised but never caught.
• For handling exceptional situations Python provides—
1. raise statement to raise user defined exception in the program.
2. try... except statement for catching and handling errors
raise Statement:
• raise statement allows the program to force a specified exception to occur at run-time.
• It allows to raise an user-defined exception in the try block.
• Syntax:
raise [exception name [, message/argument][, traceback]]
• Example:
a=int (input(“Enter a positive number:”))
if a<0:
raise Exception(“Please enter a positive number”)
else:
print(“You have entered a positive number”)
EXCEPTION HANDLING METHODS
Method 1: Using try…… except block
• We can handle exceptions using try……except statement.
• We put our usual statements within try block and put all our error handlers in the except block.
• The except block indicates the action to take when the given type of exception is raised within the
corresponding try block.
• If no exception is raised, except block is skipped.
• If an exception is raised, rest of the statements in try block is skipped and execution jumps to the
first statement within that except block. If there is no corresponding except block, the program
terminates.
• If we are using try block in our program, there must be at least one except block, otherwise shows
error “expected except or finally block”.
• Syntax of try…….except statement is:
try:
statements inside try block
except ExceptionName:
statements to be evaluated in case of ExceptionName happens
EXAMPLE

try: n1=int(input(“Enter First Number:”))


n1=10 n2=in(input(“Enter Second Number:”))
n2=40 try:
print(n1+n4) d=n1/n2
print(d)
except NameError: except ZeroDivisionError:
print("Invalid print("n2 should be greater than zero")
Variable")
Method 2:using try with multiple except blocks
• The try statement may have multiple except blocks with Exception Names to handle
specific exceptions and one optional except clause.
• The control is transferred to the corresponding except block handling the exception
which has occurred.
• If that particular exception (which has occurred) is not specified in any except block,
then the control is transferred to the except block without any exception name.
• If neither of the above two cases are met (there is no except clause handling that
particular exception and there is no except clause without any exception name), then
the script terminates abruptly.
Syntax

try:
You do your operations here
......................
except Exception (Name) – I:
If there is exception-I, then execute this block.
except Exception (Name) – II:
If there is exception-II, then execute this block.
except Exception (Name) – III:
If there is exception III, then execute this block.
......................
except:
If there is no exceptions with the specified name given above, then execute this
block.
Example
try:
num1=int(input(“Enter Dividend:”))
num2=int(input(“Enter Divisor:”))
num3=num1//num2 Output
Enter Dividend:10
print(“Quotient is”,num3) Enter Divisor:5
Quotient is 2
except ValueError: Enter Dividend:25
print(“Please enter a valid value”) Enter Divisor:0
Division by Zero is not possible
except ZeroDivisionError: Enter Dividend:10
print(“Division by Zero is not possible”) Enter Divisor: z
Please enter a valid value
except:
print(“An error occurred”)
Method 3: using try…. except with else block
• We can put an optional else clause along with try…..except clause.
• The else clause of try statement is used to specify the code which is executed in case no
exception occurs.
• If exception occurs, else part will not be executed.
• Syntax:
try:
You do your operations here
......................
except Exception:
If there is exception, then execute this block.
else:
If there is no exception, then execute this block
Example
try:
num1=int(input(“Enter Dividend:”))
num2=int(input(“Enter Divisor:”))
Output
num3=num//num2 Enter Dividend:10
print(“Quotient is”,num3) Enter Divisor:5
Quotient is 2
except ValueError: Program executes successfully
print(“Please enter a valid value”) Enter Dividend:25
Enter Divisor:0
except ZeroDivisionError: Division by Zero is not possible
print(“Division by Zero is not possible”) Enter Dividend:10
Enter Divisor: z
except TypeError: Please enter a valid value
print(“Datatypes do not match”)
else:
print(“Program executes successfully”)
Method 4: using try….except with finally block
• The finally block is called clean-up or termination clause because it is executed
under all circumstances.
• i.e., a “finally” block is always executed irrespective of whether an exception has
occurred in a try block or not.
• If used, finally should be placed at end of try clause, after all except blocks and else
block.
• Syntax:
try:
You do your operations here
......................
except Exception-I:
If there is exception-I, then execute this block.
except Exception-II:
If there is exception-II, then execute this block.
......................
:
else:
If there is no exceptions, then execute this block.
finally:
Always executed.
Example
try:
num1=int(input(“Enter Dividend:”))
num2=int(input(“Enter Divisor:”))
num3=num//num2
print(“Division performed successfully”) Output
Enter Dividend:10
except ValueError:
Enter Divisor:5
print(“Please enter a valid value”) Division performed successfully
except ZeroDivisionError: Quotient is 2
print(“Division by Zero is not possible”) Program ends
except TypeError:
print(“Datatypes do not match”)
else:
print(“Quotient is “num3)
finally:
print(“Program ends”)
ACTIVITY
• Consider the code given below and fill in the blanks:
print(“Learning Exceptions…….”)
try:
num1=int(input(“Enter First Number:”))
num2=int(input(“Enter Second Number:”))
quotient=num1/num2
print(“Both numbers entered correctly”)
except _________: # to enter only integers
print(“Please enter only numbers”)
except _________: # Denominator cannot be zero
print(“Number 2 should not be zero”)
else:
print(“Well Done!!!”)
_______: # to be executed at the end
print(“Program Ends”)
ACTIVITY

What will be the output of the following program?


x, y, a = 5,0,None
print ("a")
try:
print("b")
a = x/y
print("c")
except:
print ("d")
print ("e")
print (a)
ACTIVITY
What will be the output of the following Python code? Explain the try and except used
in the code.
A=0
B=6
print('One')
try:
print('Two’)
X=8/A
print('Three')
except ZeroDivisionError:
print (B*2)
print ('Four')
except:
print (b*3)
print ('Five')
LET’S RECAP…..

• Types of Errors
• How to handle errors in python programs.

You might also like