0% found this document useful (0 votes)
33 views8 pages

Chapter1 Notes Puc

The document provides an overview of exception handling in Python, explaining the types of errors that can occur, including syntax errors and exceptions. It details built-in exceptions, user-defined exceptions, and the use of the raise and assert statements to manage errors. Additionally, it covers the process of handling exceptions using try-except blocks, including the use of else and finally clauses for comprehensive error management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views8 pages

Chapter1 Notes Puc

The document provides an overview of exception handling in Python, explaining the types of errors that can occur, including syntax errors and exceptions. It details built-in exceptions, user-defined exceptions, and the use of the raise and assert statements to manage errors. Additionally, it covers the process of handling exceptions using try-except blocks, including the use of else and finally clauses for comprehensive error management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

II PUC CS Notes

Exception Handling in Python

Introduction:
▪ An Error in a program is a mistake that prevents the program from executing.

▪ Errors in Python can occur due to syntax errors, runtime errors, or logical errors, causing the program to
either fail or produce unexpected results.

▪ In Python, exceptions are automatic errors triggered during execution, but they can also be forcefully
triggered and managed using exception handling techniques to prevent abnormal program behavior.

Syntax Errors:
▪ The Errors that occur when we have not followed the rules of the particular programming language while
writing a program are called Syntax Errors.

▪ These errors are also known as parsing errors.

▪ When a syntax error is encountered while working in shell/interactive mode, Python displays the name of
the error and a small description about the error.

▪ Similarly, when a syntax error is encountered while running a program in script mode, a dialog box
specifying the name of the error a small description about the error is displayed.

Exceptions
An Exception is an error that occurs during the execution of program even if program is syntactically correct.

An exception is a Python object that represents an error.

For example, trying to open a file that does not exist, division by zero and so on.

Built-in Exceptions

Commonly occurring exceptions are usually defined in the compiler/interpreter are called built-in exceptions.

Some of the commonly occurring built-in exceptions that can be raised in Python are:

SyntaxError - It is raised when there is an error in the syntax of the python code.
Eg:

SAMPUC |IRSHAD
II PUC CS Notes

ValueError - It is raised when a built in method or operation receives incorrect or inappropriate values

IOError - It is raised when the file specified in the program cannot be opened

KeyboardInterrupt - It is raised when the user accidentally hits the Delete or Esc key while executing a
program.

Output:

ImportError - It is raised when the requested module is not found.

EOFError - It is raised when the end of file condition is reached without any data by input().

ZeroDivisionError - It is raised when the denominator in a division operation is zero.

SAMPUC |IRSHAD
II PUC CS Notes

IndexError - It is raised when the index or subscript in a sequence is out of range

NameError - It is raised when a local or global variable is not defined.

IndentationError - It is raised due to incorrect indentation in the program code.

TypeError - It is raised when an operator is supplied with a value of incorrect data type.

OverFlowError - It is raised when the result of a calculation exceeds the maximum limit for numeric data
type.

Output:

SAMPUC |IRSHAD
II PUC CS Notes

User-defined exceptions: A programmer can also create custom exceptions to suit one’s requirements. These
are called user-defined exceptions.

The raise statement :


▪ The raise statement is used to forcefully raise/trigger an exception in python
▪ Once an exception is raised, no further statements in the current block are executed
▪ Raising an exception interrupts the normal flow of program and jumps to the code written to handle
such exceptions

Syntax of raise statement:


raise exception-name[(optional-argument)]
Eg1: raise Exception(“OOPs:Something went wrong”)

Eg2: x=-5
If x<5:
raise ValueError(“x cannot be negative”)
Eg3: def divide(a,b):
If b==0:
raise ZeroDivisionError(“Denominator cannot be zero”)
return a/b
print(divide(10,0))

The assert statement :


▪ The assert statement is used to test an expression in program code. If the result of expression is
False, it raises AssertionError.
▪ It is generally used in the beginning of a function or after a function call to check if the input is valid

Syntax of assert statement:


assert Expression[,arguments]

Eg1: print("use of assert statement")


def negativecheck(number):
assert(number>=0), "OOPS... Negative Number"
print(number*number)
print(negativecheck(100))
print(negativecheck(-350))
Eg2: email=”userexample.com”
assert “@” in email, “Invalid email”
Eg3: denominator = 0
assert denominator!=0, “Denominator cannot be zero”

Handling Exceptions:

The process of dealing with errors in a program by finding and handling exceptions, stopping the program
from crashing, and giving users helpful messages or instructions is known as exception handling.

Need for Exception Handling:


▪ It is a useful technique that helps in capturing runtime errors and handling them so as to avoid the
program getting crashed

SAMPUC |IRSHAD
II PUC CS Notes

▪ Python categorises exceptions into distinct types so that specific exception handlers can be created for
each type.
▪ Exception handlers separate the main logic of the program from the error detection and correction
code. These statements for detection and reporting the exception do not affect the main logic of the
program.
▪ The compiler or interpreter keeps track of the exact position where the error has occurred.
▪ Exception handling can be done for both user-defined and built-in exceptions

Process of Handling Exception:

➢ When an error occurs, Python interpreter creates an object called the exception object. This object
contains information about the error like its type, file name and position in the program where the error
has occurred.
➢ The object is handed over to the runtime system so that it can find an appropriate code to handle this
particular exception
➢ It first searches for the method in which the error has occurred and the exception has been raised. If
not found, then it searches the method from which this method (in which exception was raised) was
called. This hierarchical search in reverse order continues till the exception handler is found.
➢ The list of methods searched is called the call stack, and when a suitable handler is found, it is executed
by the runtime system.
➢ If the runtime system is not able to find an appropriate exception handler after searching all the methods
in the call stack, then the program execution stops

SAMPUC |IRSHAD
II PUC CS Notes

Catching Exceptions:

➢ An exception is said to be caught when a code that is designed to handle a particular exception is
executed.
➢ 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 are written inside the except clause

Syntax of try..except block:

try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is encountered]

Eg:
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print(quotient)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO.... not allowed")
print(“OUTSIDE try..except block”)

In the above code if the user enters the value of denom as zero (0), then the execution of the try block will
stop. The control will shift to the except block and the message “Denominator as Zero…. not allowed” will
be displayed.

Defining multiple except clauses:

Sometimes, a single piece of code might be suspected to have more than one type of error. For
handling such situations, we can have multiple except blocks for a single try block.

Eg:

try:
numerator=50
denom=int(input("Enter the denominator: "))
print (numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")

try...except…else clause

➢ An optional else clause can also be used along with the try...except clause.
➢ It is executed if there is no error detected in the try block

SAMPUC |IRSHAD
II PUC CS Notes

Eg: print ("Handling exception using try...except...else")


try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)

Finally Clause:
➢ The try statement in Python can also have an optional finally clause.
➢ The statements inside the finally block are always executed regardless of whether an exception has
occurred in the try block or not.
Eg:

print ("Handling exception using try...except...else...finally")


try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
except ValueError:
print ("Only INTEGERS should be entered")
else:
print ("The result of division operation is ", quotient)
finally:
print ("Execution completed")

Recovering and continuing with finally clause:


In the program if the exception is not handled by any of the except clauses, then it is re-raised after the
execution of the finally block.

SAMPUC |IRSHAD
II PUC CS Notes

Eg:
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed")
else:
print ("The result of division operation is ", quotient)
finally:
print ("Execution completed")

While executing the above code, if we enter a non-numeric data as input, the finally block will be executed.
So, the message “Execution completed” will be displayed. Thereafter the exception for which handler is not
present will be re-raised.

SAMPUC |IRSHAD

You might also like