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

Python Module5 ErrorHandling Notes

Uploaded by

emily16852.9a
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)
4 views12 pages

Python Module5 ErrorHandling Notes

Uploaded by

emily16852.9a
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

PYTHON PROGRAMMING

Error and Exception Handling


Types of Errors in Python
In Python, errors can be broadly classified into three main categories:

1.1 Syntax Errors (Compile-Time Errors)


Syntax errors occur when the Python interpreter finds code that does not conform to the language grammar.
These are detected before the program runs.

Example 1.1: Syntax Error


# Missing colon at the end of if statement
x = 10
if x > 5 # SyntaxError: invalid syntax
print('Greater')

OUTPUT
SyntaxError: invalid syntax

1.2 Runtime Errors (Exceptions)


Runtime errors occur during the execution of a program even if the syntax is correct. These are also called
exceptions.

Example 1.2: Runtime Error - Division by Zero


num = 10
deno = 0
result = num / deno # ZeroDivisionError at runtime
print(result)

OUTPUT
ZeroDivisionError: division by zero

1.3 Logical Errors


Logical errors produce incorrect results without raising any exception. The program runs successfully but gives
wrong output due to flawed logic.

Example 1.3: Logical Error - Wrong formula


# Intended to find area of a rectangle, but formula is wrong
length = 5
breadth = 4
area = length + breadth # Should be length * breadth
print('Area:', area)
OUTPUT
Area: 9 # Wrong! Expected: 20

NOTE: Syntax and runtime errors are caught by Python, but logical errors must be found and fixed by the
programmer through careful testing and debugging.

2. Handling Exceptions (try-except)


The try-except block is used to handle exceptions gracefully. Code that might raise an exception is placed
inside the try block, and the exception handling code goes in the except block.

2.1 Basic Syntax


SYNTAX
try:
# Code that may raise an exception
...
except ExceptionName:
# Code to handle the exception
...

2.2 Single except Block


Example 2.1: Handling ZeroDivisionError
num = int(input('Enter the numerator : '))
deno = int(input('Enter the denominator : '))
try:
quo = num / deno
print('QUOTIENT : ', quo)
except ZeroDivisionError:
print('Denominator cannot be zero')

OUTPUT
Enter the numerator : 10
Enter the denominator : 0
Denominator cannot be zero

NOTE: Exceptions give you information like what, why, and how something went wrong.

2.3 Multiple except Blocks


Python allows multiple except blocks for a single try block. The block that matches the exception generated will
get executed. Only one handler is executed per exception.

Example 2.2: Program with multiple except blocks


try:
num = int(input('Enter the number : '))
print(num ** 2)
except (KeyboardInterrupt):
print('You should have entered a number..... Program Terminating...')
except (ValueError):
print('Please check before you enter..... Program Terminating...')
print('Bye')

OUTPUT
Enter the number : abc
Please check before you enter..... Program Terminating...
Bye

NOTE: After execution of the except block, the program control goes to the first statement after the except
block for that try block.

2.4 Multiple Exceptions in a Single Block


An except clause may name multiple exceptions as a parenthesized tuple. Whatever exception is raised, if it
matches any in the tuple, the same except block will be executed.

Example 2.3: Handling multiple exceptions in one except clause


try:
num = int(input('Enter the number : '))
print(num ** 2)
except (KeyboardInterrupt, ValueError, TypeError):
print('Please check before you enter..... Program Terminating...')
print('Bye')

OUTPUT
Enter the number : abc
Please check before you enter..... Program Terminating...
Bye

PROGRAMMING TIP: No code should be present between a list of except blocks.

2.5 Except Block Without Exception (Wildcard)


You can specify an except block without mentioning any exception (i.e., except:). This acts as a wildcard and
catches all types of exceptions.

Example 2.4: Using except: without specifying exception type


try:
file = open('[Link]')
str = [Link]()
print(str)
except IOError:
print('Error occurred during Input ...... Program Terminating...')
except ValueError:
print('Could not convert data to an integer.')
except:
print('Unexpected error.... Program Terminating...')
OUTPUT
Unexpected error.... Program Terminating...

WARNING: Using except: without mentioning any specific exception is NOT a good programming
practice because it catches all exceptions and does not help the programmer identify the root cause of the
problem.

3. The else Clause


The try...except block can optionally have an else clause. The statements in the else block are executed only if
the try clause does not raise an exception. The else block must follow all except blocks.

Example 3.1: Demonstrating the else block - File found


try:
file = open('[Link]')
str = [Link]()
print(str)
except IOError:
print('Error occurred during Input ...... Program Terminating...')
else:
print('Program Terminating Successfully.....')

OUTPUT
Hello
Program Terminating Successfully.....

Example 3.2: Demonstrating the else block - File NOT found


try:
file = open('[Link]')
str = [Link]()
print(str)
except:
print('Error occurred ...... Program Terminating...')
else:
print('Program Terminating Successfully.....')

OUTPUT
Error occurred ......Program Terminating...

4. Raising Exceptions
You can deliberately raise an exception using the raise keyword. The general syntax is:

SYNTAX
raise [Exception [, args [, traceback]]]

Here, Exception is the name of the exception to be raised (e.g., TypeError). args is optional and specifies a
value for the exception argument.
Example 4.1: Deliberately raising a ValueError
try:
num = 10
print(num)
raise ValueError
except:
print('Exception occurred .... Program Terminating...')

OUTPUT
10
Exception occurred .... Program Terminating...

4.1 Re-raising an Exception


The only argument to the raise keyword specifies the exception to be raised. You can re-raise an exception from
the except block using raise without any arguments.

Example 4.2: Re-raising an exception


try:
f = open('[Link]') # opening a non-existent file
except:
print('File does not exist')
raise # re-raise the caught exception

OUTPUT
File does not exist
Traceback (most recent call last):
File '[Link]', line 2, in <module>
f = open('[Link]')
IOError: [Errno 2] No such file or directory: '[Link]'

PROGRAMMING TIP: To re-raise an exception, use the raise keyword without any arguments inside the
except block.

5. Instantiating Exceptions
Python allows programmers to instantiate an exception first before raising it and add any attributes or arguments
to it as desired. The exception instance also becomes an exception with the arguments stored in [Link].

Example 5.1: Instantiating an exception with arguments


try:
raise Exception('hello', 'world')
except Exception as errorObj:
print(type(errorObj)) # the exception instance
print([Link]) # arguments stored in .args
str = errorObj # allows args to be printed directly
print(str)
OUTPUT
<type '[Link]'>
('hello', 'world')
('hello', 'world')
Argument1 = hello
Argument2 = world

Example 5.2: Raising an exception with arguments


try:
raise Exception('Hello', 'World')
except ValueError:
print('Program Terminating....')

OUTPUT
Exceptions: ('Hello', 'World')

NOTE: If you raise an exception with arguments but do not handle it, then the name of the exception str is
printed along with its arguments.

6. Handling Exceptions in Invoked Functions


Exceptions can also be handled inside functions that are called in the try block. If the exception occurs in the
invoked function, it is handled in the try block as shown in the calling function.

A large program is usually divided into a number of functions. The possibility that the invoked function may
generate an exceptional condition cannot be ignored. The exception which is handled by the calling function —
the syntax for such a situation can be:

SYNTAX
try:
...
function_name(arg list): // function call
...
except ExceptionName:
// Code to handle exception

Example 6.1: Handling exception in the calling function


def Divide(num, deno):
return num / deno

try:
Divide(10, 0)
except ZeroDivisionError:
print('You cannot divide a number by zero... Program Terminating...')

OUTPUT
You cannot divide a number by zero... Program Terminating...

Example 6.2: Exception handled inside function


def divide(num, deno):
try:
quo = num / deno
print('You cannot divide a',
'number by zero.... Program Terminating...')
except ZeroDivisionError:
print('You cannot divide a number by zero.... Program Terminating...')

divide(10, 0)

OUTPUT
You cannot divide a number by zero.... Program Terminating...

NOTE: Irrespective of the location of the exception, the try block is always immediately followed by the
except block.

7. Built-in and User-Defined Exceptions

7.1 Built-in Exceptions


Python has a set of standard built-in exceptions that are already defined. These exceptions force your program
to output an error when something goes wrong.

Exception Description
Exception Base class for all exceptions
StopIteration Raised when next() method of iterator doesn't point to any object
SystemExit Raised by [Link]() function
StandardError Base class for all built-in exceptions (excluding StopIteration and
SystemExit)
ArithmeticError Base class for errors generated due to mathematical calculations
OverflowError Raised when the maximum limit of a numeric type is exceeded
FloatingPointError Raised when a floating point calculation cannot be performed
ZeroDivisionError Raised when a number is divided by zero
AssertionError Raised when the assert statement fails
AttributeError Raised when attribute reference or assignment fails
EOFError Raised when end-of-file is reached or no input for input() function
ImportError Raised when an import statement fails
KeyboardInterrupt Raised when the user interrupts program execution (Ctrl+C)
IndexError Raised when an index is not found in a sequence
KeyError Raised when a key is not found in the dictionary
NameError Raised when an identifier is not found in local or global namespace
IOError Raised when input or output operation fails
SyntaxError Raised when there is a syntax error in the program
IndentationError Raised when there is an indentation problem in the program
ValueError Raised when arguments passed to a function are of invalid data type
TypeError Raised when two or more data types are mixed without coercion
RuntimeError Raised when the generated error does not fall into any other category
NotImplementedError Raised when an abstract method that needs to be implemented in an
inherited class is not implemented
7.2 User-Defined Exceptions
Python allows programmers to create their own exceptions by creating a new exception class. The new
exception class is derived from the base class Exception which is pre-defined in Python.

Example 7.1: Defining a user-defined exception


class myError(Exception):
def __init__(self, val):
[Link] = val
def __str__(self):
return repr([Link])

try:
raise myError(10)
except myError as e:
print('User Defined Exception Generated with value', [Link])

OUTPUT
User Defined Exception Generated with value 10

Example 7.2: Sub-classes of Exception for customized handling


class Error(Exception):
def message(self):
raise NotImplementedError()

class InputError(Error):
def __init__(self, expr, msg):
[Link] = expr
[Link] = msg
def message(self):
print('Error in input in expression'),
print([Link])

try:
a = input('Enter a : ')
raise InputError(input('Enter a : s'), 'Input Error')
except InputError as ie:
[Link]()

OUTPUT
Enter a : 10
Error in input in expression
input("Enter a : s")

PROGRAMMING TIP: Although there is no naming convention for user-defined exceptions, it is better to
define exceptions with names that end in 'Error' to make it consistent with the naming of the standard
exceptions.
NOTE: Many standard modules define their own exceptions to report errors that may occur in functions
they define.
8. The finally Block
The finally block is an optional block that can be used with a try block to define clean-up actions that must be
executed under all circumstances. The finally block is always executed irrespective of whether an exception
has occurred or not.

SYNTAX
try:
# Write your operations here
...
# Due to any exception, operations written here will be skipped
finally:
# This would always be executed
...

Example 8.1: finally block when exception IS raised


try:
print('Raising Exception.....')
raise ValueError
finally:
print('Performing clean up in Finally......')

OUTPUT
Raising Exception.....
Performing clean up in Finally......
Traceback (most recent call last):
...
ValueError

Example 8.2: try, except, and finally together


try:
print('Raising Exception.....')
raise ValueError
except:
print('Exception caught.....')
finally:
print('Performing clean up in Finally......')

OUTPUT
Raising Exception.....
Exception caught.....
Performing clean up in Finally......

Example 8.3: finally block to re-raise exception to outer try-except


try:
print('Dividing Strings....')
try:
quo = 'abc' / 'def'
finally:
print('In finally block.....')
except TypeError:
print('In except block.. handling TypeError...')

OUTPUT
Dividing Strings....
In finally block.....
In except block.. handling TypeError...

NOTE: You cannot have an else block with a finally block.


PROGRAMMING TIP: The finally block can never be followed by an except block.

8.1 Pre-defined Clean-up Action


In Python, some objects define standard clean-up actions that are automatically performed when the object is no
longer needed. The better way to handle file objects is using the with keyword so that the file is automatically
closed when not in use.

Example 8.4: Using with statement for automatic clean-up


with open('[Link]') as file:
for line in file:
print(line)

OUTPUT
Hello
# Welcome to the world of Programming
Python is a very simple and interesting language
Happy Reading

9. Assertions in Python
An assertion is a basic check that can be turned on or off when the program is being tested. You can think of
assert as a raise-if-not statement — if the expression is False, an AssertionError is raised. Assertions are placed
at the start of a function to check for valid input, and after a function call to check for valid output.

SYNTAX
assert expression[, arguments]

If the expression evaluates to False, an exception is raised and the message will be printed on the screen. The
above statement is semantically equivalent to writing:

if not expression:
raise AssertionError(arguments)

Example 9.1: Using the assert statement - temperature check


c = int(input('Enter the temperature in Celsius : '))
f = (c * 9/5) + 32
assert(f <= 32), 'Its freezing'
print('Temperature in Fahrenheit = ', f)

OUTPUT
Enter the temperature in Celsius: 100
Traceback (most recent call last):
File '[Link]', line 3, in <module>
assert(f<=32), 'Its freezing'
AssertionError: Its freezing

Example 9.2: Assert with valid input (no exception raised)


def divide(a, b):
assert b != 0, 'Denominator cannot be zero!'
return a / b

print(divide(10, 2)) # Valid input, no exception


print(divide(10, 0)) # AssertionError raised

OUTPUT
5.0
Traceback (most recent call last):
...
AssertionError: Denominator cannot be zero!

NOTE: assert statement should be used for trapping user-defined constraints.

Key Points on Assertions


• Do not catch exceptions that you cannot handle.
• User defined exceptions can be very useful if some complex or specific information has to be stored in
exception instances.
• Do not create new exception classes when the built-in exceptions already have all the functionality you
need.

10. Exception Handling with [Link]


Python's [Link] provides an elegant way to suppress (ignore) specific exceptions. It is particularly
useful to avoid writing verbose try-except blocks for exceptions you wish to silently ignore.

SYNTAX
from contextlib import suppress

with suppress(FileNotFoundError):
[Link]('[Link]')
# Code that might raise FileNotFoundError

Example 10.1: Suppressing FileNotFoundError


import os
from contextlib import suppress

# Traditional way:
try:
[Link]('[Link]')
except FileNotFoundError:
pass
# Using suppress (cleaner):
with suppress(FileNotFoundError):
[Link]('[Link]')

Advantages of [Link]
• Ignoring non-critical exceptions: Avoids cluttering the code with complex try-except blocks for
exceptions that are not critical.
• Simplifying error handling logic: Suppressing specific exceptions allows focus on handling only the
critical ones.
• Batch operations: During batch operations on a collection of items, suppress() handle errors gracefully
without disrupting the entire batch.
• Integration with external libraries: Provides a straightforward way to ignore non-fatal exceptions from
external libraries.
• Avoiding Redundancy: Suppress the exception at the point where it is most important instead of
handling the same exception at multiple points.

WARNING: Suppressing all exceptions blindly can make debugging more challenging. We must suppress
it judiciously and document the use of [Link] in the code.

Quick Reference Summary

Keyword / Concept Purpose When Executed


try Contains code that might raise an Always executed first
exception
except Handles the raised exception When a matching exception occurs in
try
else Runs when no exception occurs Only when try block succeeds
without exception
finally Clean-up actions Always, regardless of exception
raise Deliberately raise an exception When explicitly called by the
programmer
assert Check a condition; raises When the assert expression evaluates
AssertionError if false to False
[Link] Silently ignore specific When a suppressed exception occurs
exceptions in the with block

You might also like