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

Chapter 1 Exception Handling in Python

The document provides an overview of exception handling in Python, detailing types of errors such as syntax errors and exceptions, as well as built-in exceptions. It explains how to raise exceptions using the raise and assert statements, and outlines the process of handling exceptions with try, except, else, and finally blocks. The document emphasizes the importance of exception handling in preventing program crashes and improving 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)
3 views7 pages

Chapter 1 Exception Handling in Python

The document provides an overview of exception handling in Python, detailing types of errors such as syntax errors and exceptions, as well as built-in exceptions. It explains how to raise exceptions using the raise and assert statements, and outlines the process of handling exceptions with try, except, else, and finally blocks. The document emphasizes the importance of exception handling in preventing program crashes and improving 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

MEGHARAJ K, Lecturer in C.

S, JAIHIND PU COLLEGE
CHAPTER – 1
EXCEPTION HANDLING IN PYTHON

1. Introduction
2. Syntax Errors
3. Exceptions
4. Built-in Exceptions
5. Raising Exceptions
6. Handling Exceptions
7. Finally Clause

INTRODUCTION
While executing a Python program, sometimes the program may not run or may give incorrect
output. These problems occur due to errors in the code.
There are three types of errors:
 Syntax Errors
 Runtime Errors (Exceptions)
 Logical Errors
An exception is an error that occurs during program execution. Python automatically generates
exceptions, and they can also be handled using code.

SYNTAX ERRORS
 Definition: A syntax error occurs when the rules of Python programming are not followed
while writing the code.
 These errors are also called parsing errors because they are detected while the Python
interpreter is reading (parsing) the code.

Common Causes of Syntax Errors:


 Missing colon (:) after statements like if, for, while
 Incorrect indentation
 Missing brackets or quotes
 Spelling mistakes in keywords

Example 1:
if x > 5 if x > 5:
print("Hello") print("Hello")
Error: Missing colon

Example 2:
print("Hello) print("Hello")
Error: Missing closing quotation mark

Page | 1
MEGHARAJ K, Lecturer in C.S, JAIHIND PU COLLEGE
EXCEPTIONS
 Definition: Even if a program is written correctly (no syntax errors), errors may still occur
during execution. These errors interrupt the normal flow of the program and are called
exceptions.
 An exception is an object in Python that represents an error. When such an error occurs
during execution, it is said that an exception is raised.

BUILT-IN EXCEPTIONS
Some exceptions occur frequently in programs. Python provides predefined exceptions to
handle such common errors. These are called built-in exceptions.

Common Built-in Exceptions:


No Exception Name Explanation
1. SyntaxError Raised when there is an error in the syntax of the program.
2. ZeroDivisionError Raised when a number is divided by zero.
3. ValueError Raised when the correct data type is used, but the value is inappropriate.
4. TypeError Raised when an operation is performed on incompatible data types.
5. ImportError Raised when a required module cannot be imported.
6. IndexError Raised when an index is out of range in a sequence.
7. NameError Raised when a variable name is not defined.
8. IOError Raised when a file cannot be opened or accessed.
9. KeyboardInterrupt Raised when the user interrupts the program execution (e.g., pressing
Esc/Delete).
10. EOFError Raised when input() reaches end-of-file without reading data.
11. IndentationError Raised due to incorrect indentation in the code.
12. OverflowError Raised when a calculation exceeds the maximum limit of a numeric data
type.

Page | 2
MEGHARAJ K, Lecturer in C.S, JAIHIND PU COLLEGE
RAISING EXCEPTIONS
In Python, exceptions are automatically raised when errors occur. However, programmers can
also forcefully raise exceptions using:
 raise statement
 assert statement
Raising an exception means:
 Interrupting the normal flow of the program
 Skipping remaining statements in the current block

THE RAISE STATEMENT


The raise statement is used to explicitly generate an exception in a program.
Syntax:
raise ExceptionName("Message")
 ExceptionName → Name of the exception
 Message → Optional description

Example:
ZeroDivisionError Without using raise statement
a = 10
b = 0

result = a / b
print(result)

Output:
ZeroDivisionError: division by zero

ZeroDivisionError With using raise statement


a = 10
b = 0

if b == 0:
raise ZeroDivisionError("Sorry.. Cannot divide by zero")
else:
result = a / b
print(result)

Output:
ZeroDivisionError: Sorry.. Cannot divide by zero

Page | 3
MEGHARAJ K, Lecturer in C.S, JAIHIND PU COLLEGE
THE ASSERT STATEMENT
The assert statement is used to test an expression (condition) in a program. If the condition is
false, Python raises an AssertionError.
It is mainly used:
 To check valid input
 At the beginning of a function or after a function call

Syntax:
assert expression, "Error Message"
 expression → Condition to be tested
 message → Optional message displayed if condition is false

Example:
print("use of assert statement")

def negativecheck(number):
assert (number >= 0), "OOPS... Negative Number"
print(number * number)

negativecheck(4)
negativecheck(-5)
 When negativecheck(4) is called → condition is true → output is printed
 When negativecheck(-5) is called → condition is false
Python raises AssertionError
Message "OOPS... Negative Number" is displayed
Further execution will stops

HANDLING EXCEPTIONS
Exception Handling
Exception handling is the process of detecting and managing errors (exceptions) that occur
during program execution.
In Python, exception handling is done using:
 try
 except
 else
 finally blocks

Need for Exception Handling


 Prevents program from crashing
 Separates normal code from error-handling code
 Helps identify exact error location
 Works for both built-in and user-defined exceptions

Page | 4
MEGHARAJ K, Lecturer in C.S, JAIHIND PU COLLEGE
Process of Handling Exceptions
When an error occurs:
1. Python creates an exception object
o Contains error type, message, and location
2. The exception is raised (thrown)
3. The runtime system searches for a handler
4. Search starts from current method and moves backward
o This sequence is called the call stack
5. If handler is found → exception is caught and handled
6. If no handler is found → program terminates

Page | 5
MEGHARAJ K, Lecturer in C.S, JAIHIND PU COLLEGE
try...except Block
Syntax:
try:
# Code that may cause error
except ExceptionType:
# Code to handle error

Example:
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 is not allowed")

print("OUTSIDE try..except block")

Multiple except Blocks


Example:
try:
num = int(input("Enter a number: "))
result = 10 / num

except ZeroDivisionError as e:
print("Error: Division by zero -", e)

except ValueError as e:
print("Error: Invalid input -", e)

Generic except Block


try:
num = int(input("Enter a number: "))
result = 10 / num

except Exception as e:
print("An error occurred:", e)

Page | 6
MEGHARAJ K, Lecturer in C.S, JAIHIND PU COLLEGE
try...except...else Block
try:
numerator = 50
denom = int(input("Enter the denominator: "))
quotient = numerator / denom

except ZeroDivisionError:
print("Denominator as ZERO is not allowed")

except ValueError:
print("Only integers should be entered")

else:
print("The result is", quotient)

FINALLY CLAUSE
The finally block is used with try-except to execute code always, whether an exception occurs
or not.

Syntax:
try:
# Risky code
except:
# Handling code
finally:
# Always executed

Example:
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 is", quotient)
finally:
print("OVER AND OUT")

Page | 7

You might also like