0% found this document useful (0 votes)
0 views12 pages

Chapter 1

Chapter 7 discusses exception handling in Python, explaining how it allows programs to manage runtime errors without crashing. It covers various types of errors, including syntax errors and built-in exceptions, as well as techniques for raising and handling exceptions using try, except, else, and finally blocks. The chapter emphasizes the importance of structured error management to improve program reliability and user experience.
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)
0 views12 pages

Chapter 1

Chapter 7 discusses exception handling in Python, explaining how it allows programs to manage runtime errors without crashing. It covers various types of errors, including syntax errors and built-in exceptions, as well as techniques for raising and handling exceptions using try, except, else, and finally blocks. The chapter emphasizes the importance of structured error management to improve program reliability and user experience.
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/ 12

Chapter 7: Exception Handling in Python

Chapter 7: EXCEPTION HANDLING IN PYTHON


Topics
• Introduction
• Syntax Errors
• Exceptions
• Built-in Exceptions
• Raising Exceptions
• Handling Exceptions
• Finally Clause

Introduction to Exception handling:


• Exception Handling in Python is a mechanism to handle runtime errors, allowing a program
to continue executing even after encountering an error.
• Sometimes, when running a Python program, it might not run at all or give wrong results
because of errors in the code.
• Exception handling helps by catching these errors, so the program doesn't crash. This way,
you can manage errors smoothly and keep the program running.
• Exception Handling is a feature in Python that allows us to handle errors and prevent the
program from crashing
• Errors are problems due to which the program will stop the execution.
• It may be due to syntax, runtime or logical errors.

Syntax Errors:
• Syntax errors occur when we have not followed the rules/syntax of a particular
programming language while writing a program. These are grammatical mistakes made.
• Examples of syntax errors include missing parenthesis, quotation marks etc.

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

Exception
• Exception is an unexpected event that occurs during the execution of a program. It is an
error that occurs during runtime.
• Exception is a python object that represents an error. Even if the statement is syntactically
correct, there might be a situation in which an exception may occur.
• Examples are dividing by O, accessing a variable without defining it, trying to open a non-
existing file.
• Commonly occurring exceptions are usually defined in the compiler/interpreter. These are
called built-in exceptions.
• The programmer then has to take appropriate action to handle the exception.

SyntaxError: Raised when there is a mistake in the syntax of the Python code.
Example: print("Hello, world!"
A SyntaxError will be raised because the closing parenthesis is missing.

ValueError: Occurs when a function gets the correct type of argument but with an invalid value.
Example: int("Hello")
This will raise a ValueError because the string "Hello" cannot be converted into an
integer due to the presence of non-numeric characters.

IOError: Raised when a specified file cannot be opened.


Example: file = open("Creative.txt", "r")
If the file "Creative.txt" does not exist, it will raise an IOError.

KeyboardInterrupt: Triggered when the user interrupts program execution, such as by pressing
Delete or Esc.
Example: while True:
pass # Infinite loop
If you run this, the program will keep running indefinitely. When you press Ctrl+C, a
KeyboardInterrupt will be raised, stopping the program.

ImportError: Raised when a module definition cannot be found during an import operation.
Example: import scientific_maths
If the module scientific_maths does not exist, you will encounter an ImportError.
import math as m
print(m.exp(1000))

EOFError: Occurs when input() reaches the end of a file without reading any data.
Example: input("Enter a number: ")

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

It will raise an EOFError when the input() function reaches the end of the file without
reading any data.

ZeroDivisionError: Raised when a operation is attempted with zero denominator. division as the
Example: div = 10/0
This line attempts to divide 10 by 0, which is not allowed in math, ZeroDivisionError.
SO Python raises a

IndexError: Occurs when trying to access an index that is out of range in a sequence like a list or
tuple.
Example: list1 = [1, 2, 3, 4, 5]
print(list1[10])
When you try to access list1 [10],it results in an IndexError because there is no
element at that index.

NameError: Raised when a variable or name is used before being defined.


Example: x = 10
print("value is =", a)
x is defined and set to 10, but a has not been defined anywhere in the code. When
you attempt to print a, Python raises a NameError because it does not recognize a.

IndentationError: Occurs when there is incorrect indentation in the code.


Example: if True:
print("Creative Coding!")
In this example, the print statement is not indented. Python expects the statements
inside the if block to be indented, so it raises an IndentationError.

TypeError: Triggered when an operation or function is applied to an object of an incorrect type.


Example: x=5
y = "hello"
result = x + y
Here, Python raises a TypeError because you cannot add an integer (5) and a string
("hello").

OverflowError: Raised when the result of a calculation is too large for the data type to handle.
Example: import math result = math.exp(1000)
In this example, the math.exp(1000) function tries to compute e1000, which is too
large to represent as a floating-point number, leading to an OverflowError.

Raising exceptions
• Exceptions handlers are designed to execute when a specific exception is raised.

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

• Programmers can also forcefully raise exceptions in a program using the raise and assert
statement in the current block of code is executed.
• So, raising an exception involves interrupting the normal flow execution of program and
jumping to that part of the program which is written to handle such exceptional situations.
In Python raise keyword is used to raise exceptions or errors.
The raise keyword raises an error and stops the control flow of the program.
Syntax:
raise exception_name [(optional argment)]
The argument is generally a string that is displayed when the exception is raised.

Example:
a=5
if a % 2! = 0
raise exception ("the number should not be an odd integer")
Use of the raise statement to throw exception

Index Error
Python an index error means that when a code is trying to access an index that because the index
goes out of bounds by being too large.

Advantages of the raise keyword


• To handle invalid data or situations.
• To give clear error messages.
• To make the program safer and easier to debug.
• It helps to stop wrong data from being processed

Stack traceback
Stack traceback is a structured block of text that contains information about the sequence of
function calls that have been mode in the branch of execution of code in which the
exception was raised.

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

Assert statement
An assert statement in python is used to test an expression in the program code. If the result after
testing comes false, then the exception is raised. This statement is generally used in the beginning
of the function or after a function call to check for valid input.
OR
Assertion are simply Boolean expression that check if the condition return true or not. If it is true,
the program does nothing and moves to the next line of code. If it is false the program stops
and throws an error.

Syntax and Example for assert statement


Syntax

Assert expression [, arguments]

Example:

Program: Use of assert statement

print ("use of assert statement")

def negativecheck (number):

assert (number>=0), “OOPS Negative Number”

print (number * number)

print (negativecheck (100))

print (negativecheck) (-350))

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

Two ways using Assert statement


a) Assert statement has a condition and if the condition is not satisfied the program will stop
and give assertion error.
b) Assert statement can also have a condition and a optional error message. If the condition is
not satisfied assert stops the program and gives assertion error along with
the error message.

EXCEPTION HANDLING:
Exception Handling is a programming technique used to detect and manage errors that occur
during the execution of a program.
By writing additional code in a program to give proper messages or instructions to the user on
encountering an exception. This process is known as exception handling.

Need for Exception handling


• Python categorizes exceptions into different types so that specific exception handlers be
created for each type.
• The compiler or interpreter keeps track of the exact position where the error has occurred
• It can done for both user-defined and built-in exceptions

Process of Handling Exception


Error Occurrence: When an error occurs in the code, the Python interpreter detects it.
Creating Exception Object: The interpreter creates an exception object that contains information
about the error, such as: Type of error, File name, Location in the program where the error
occurred
Throwing an Exception: This exception object is passed to the runtime system. This action is called
"throwing an exception."
Control Shift: When an exception is thrown, control jumps to the exception handler, and the
remaining program statements are not executed.
Searching for Exception Handler: The runtime system looks for a block of code, known as an
exception handler, that can handle the raised exception:
• It first checks the function where the error occurred.
• If no handler is found, it moves to the function that called it.
• This reverse search continues until an appropriate handler is found.
Call Stack: The list of methods checked during this search is called the call stack.
The call stack is a data structure that keeps track of the sequence of function calls in a program.

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

When a function is called, it is added to the top of the stack, and when the function finishes
executing, it is removed from the stack.
Catching the Exception: When a suitable handler is found, the runtime system executes that
handler. This process is known as "catching the exception."
Ending Program Execution: If the runtime system cannot find any suitable handler after searching
all methods in the call stack, the program will stop running.

Example:
def divide(a, b):
return a/b
def calculate():
try:
result = divide(10, 0)
except ZeroDivisionError:
print("Cannot divide by zero!")
calculate()

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

Syntax of Exception Handling:


try:
#Code that may cause Exception
except [Exception Name]: #ExceptionName is optional
#Handling of Exception
else: (optional)
#Execute only if there is no Exception
finally: (optional)
#Code that always executes

Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")

Explanation:
• try block asks for user input and tries to divide 100 by the input number.
• except blocks handle ZeroDivisionError and ValueError.
• else block runs if no exception occurs, displaying the result.
• finally block runs regardless of the outcome, indicating the completion of execution.

Try, Except, else and finally block


• The try block allows you test the block of code for errors.
• The except block allows us to handle the exceptions.
• The else block allows us to execute the code when there is no error/exception.
• The finally block lets you execute the code regardless of the result of try and except block.

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

• Statements that may cause exceptions are kept in try block and those that handle them are
kept in A except block.

Catching Exception
• 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 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]

Consider the Program 1-2 given below:


Program 1-2 Using try..except block
print ("Practicing for try block")
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”)

Program 1-3 Use of multiple except clauses


print ("Handling multiple exceptions")

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

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

Program 1-4 Use of except without specifying an exception


print ("Handling exceptions without naming them")
try:
numerator=50
denom=int(input("Enter the denominator"))
quotient=(numerator/denom)
print ("Division performed successfully")
except ValueError:
print ("Only INTEGERS should be entered")
except:
print(" OOPS.....SOME EXCEPTION RAISED")
try: try:
a = float(input("Enter the numerator: ")) a = float(input("Enter the numerator: "))
b = float(input("Enter the denominator: ")) b = float(input("Enter the denominator: "))
div = a / b div = a/b
print("The quotient is:", div) print("The quotient is:", div)
except ZeroDivisionError: except ZeroDivisionError:
print("Error: Cannot divide by zero!") print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter valid numbers.")
except:
print("Oops... Some exception raised")
Output: Output:
Enter the numerator: 20 Enter the numerator: 20
Enter the denominator: 0 Enter the denominator: [1, 2]
Error: Cannot divide by zero! Oops... Some exception raised

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

Using of try-except-else clause:


• In Python we can also use the else clause on the try- except clause which must be present
after all the except clauses.
• An except block will be executed only if some exception is raised in the try block.
• The code enters the else clause only if the try-clause doesn't raise an exception.

Program 1-5 Use of else clause


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:
• Finally block is always executed regardless of whether an exception has occurred or not.
• Finally block should always be placed at the end of try clause, after all except blocks
and the else block.

SUNIL D N | KSVK PU COLLEGE


Chapter 7: Exception Handling in Python

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 ("OVER AND OUT")

Recovering and continuing with finally clause


If an error has been detected in the try block and the exception has been thrown, the appropriate
except block will be executed to handle the error.
But if the exception is not handled by any of the except clauses, then it is re-raised after the
execution of the finally block.
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")
else:
print("The result of the division operation is", quotient)
finally:
print("OVER AND OUT")

SUNIL D N | KSVK PU COLLEGE

You might also like