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

Exception Handling in Python

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)
27 views8 pages

Exception Handling in Python

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

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=”[Link]”
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

Common questions

Powered by AI

Syntax errors occur when the rules of the programming language are not followed, and they prevent the code from being compiled. Python addresses syntax errors by displaying the error type and a brief description when encountered . In contrast, exceptions are errors that occur during program execution even if the syntax is correct. Python handles exceptions using try-except blocks to catch and manage them, allowing the program to continue running despite errors .

Python's exception handling framework significantly enhances code maintainability and reliability by separating error management from core logic, which reduces code complexity and improves readability. Exception handling also prevents program crashes by gracefully resolving error states, thereby increasing reliability. By providing detailed error context through exception objects, it aids in debugging and future code modifications. This structure leads to cleaner, more efficient, and adaptable codebases .

The try-except-else-finally clauses in Python provide a comprehensive framework for handling exceptions. The try block contains code that might raise exceptions; if exceptions occur, control passes to the corresponding except block where specific handlers address different exceptions. The else block runs if no exceptions are raised, allowing execution of code that depends on the successful completion of the try block. Finally, the finally block executes irrespective of whether an exception occurred, useful for cleanup operations like closing files. For example, measuring a defined code block’s success can be structured with 'try' for execution, 'except' for error correction, 'else' for desired output upon success, and 'finally' for post-operation cleanup .

The raise statement in Python is used to deliberately raise exceptions at specific points in the program, providing finer control over error handling. Raising an exception interrupts the program's normal flow and transfers control to the nearest exception handler. For example, 'raise ValueError("x cannot be negative")' forces a ValueError when a variable x is less than a specified value, allowing developers to preemptively handle error conditions before they propagate .

Multiple except clauses in a single try-except block allow for specific handling of different exception types arising from a single block of code, enhancing flexibility and precision in error management. By allowing distinct blocks for different exceptions, developers can provide tailored responses, leading to more efficient exception handling. This granularity aids in reducing unnecessary exception checks, streamlining logic, and addressing each error type appropriately, which in turn supports improved debugging and maintenance practices .

User-defined exceptions in Python are important because they provide customized error handling tailored to specific conditions that built-in exceptions might not cover adequately. They can be created by defining a new exception class derived from the Exception class. For effective implementation, clear and meaningful exception messages and attributes should be included to convey sufficient context about the error. This practice helps maintain program robustness by addressing unique error conditions beyond standard exceptions .

The assert statement in Python is used to test conditions and automatically raise an AssertionError if the condition is False. It is particularly useful in debugging or in the initial stage of function calls to ensure that conditions such as preconditions are met. For instance, asserting 'assert number >= 0' ensures the variable 'number' is non-negative . It is preferable over try-except when the failure of the condition is unexpected and indicates a bug because it stops execution and highlights logical errors rather than runtime issues.

The 'finally' block in Python's exception handling is crucial for resource management and ensuring predictable termination since it executes regardless of whether an exception occurs. This makes it ideal for closing files, releasing resources, or executing any necessary cleanup actions that must occur after a try-except block, ensuring that resources do not leak and that program environments are restored to a stable state regardless of the outcome of preceding blocks .

When an exception is raised, Python's runtime system creates an exception object with information like error type and location. It then performs a hierarchical search called 'walking through the call stack' to find the nearest suitable exception handler. It starts with the method where the error occurred, moving upwards to called methods, searching for a handler with a matching exception type. If no matching handler is found throughout the call stack, the program terminates .

The call stack in Python's exception handling is a list of method calls that the runtime system searches in reverse order to find an appropriate exception handler when an error occurs. If an exception is not handled in the current method, the search continues up the call stack until a handler is found. This systematic approach helps ensure that exceptions are managed effectively, stopping program execution only if no handler is located in the stack .

You might also like