Python Tutorial: Exception Handling

Wednesday, 23 April 2025

Exception Handling

Exception Handling:

Sometimes while executing a Python program, the program does not execute at all or the program executes but generates unexpected output or behaves abnormally. These occur when there are syntax errors, runtime errors or logical errors in the code. In Python, exceptions are errors that get triggered automatically. However, exceptions can be forcefully triggered and handled through program code.

SYNTAX ERROR

SEMANTIC ERROR

LOGICAL ERROR

RUN TIME ERROR

It occurs when we put some incorrect punctuation, incorrect word sequence or there are some undefined terms or missing parenthesis.

Syntax errors are also called as Parsing errors.

 

For example:

>>> p=2(num1+num2)

This statement is mathematically correct but python interpreter will raise SYNTAX error as there is no sign present between 2 and parenthesis. The correct statement will be:

>>> p=2*(num1+num2)

It occurs when the code is correct according to syntax but it is not meaningful. The code will not behave as expected.

 

For example:

A = 10

B = ”hello”

Result = A + B

Here, The code will execute as it has correct syntax but will not generate expected output.

It may occur when there may be some improper sequence of statements or incorrect use of operator. It will not stop a program from executing but will produce incorrect output. It will generate incorrect output for every value of input.

 

For example:

If we want to find sum of two numbers and write the following code:

A, B = 10, 15

C = A * B

print (“Sum is: “, C)

Here, the code will generate A * B but we wanted to find Sum. Hence it is a logical error.

It occurs at the time of program execution. Such errors produce incorrect output for specific values of input. These errors are also called Exceptions, which occur when something unexpected happens leading to stop the program execution.

 

For example:

5. Division by zero

6. Finding square root of negative number.

7. Insufficient memory available on computer.

8. Trying to open a file that does not exist.

 

Handling Exceptions Using Try-Except Blocks

The fundamental construct for handling exceptions in Python is the `try-except` block. It

allows you to define a section of code (the "try" block) where you anticipate exceptions might

occur. If an exception occurs within the "try" block, Python immediately jumps to the

associated "except" block, where you can define how to handle the exception.

Here's the syntax for a basic `try-except` block:

try:

# Code that may raise an exception

except ExceptionType:

# Code to handle the exception

- `try`: This block contains the code that might raise an exception.

- `except ExceptionType`: If an exception of the specified type occurs in the "try" block, the

code within the "except" block will execute to handle the exception.

Example 1: Handling Division by Zero

try:

numerator = 10

denominator = 0

result = numerator / denominator # This may raise a ZeroDivisionError

except ZeroDivisionError:

print("Error: Division by zero.")

Example 2: Handling File Not Found

try:

file = open("non_existent_file.txt", "r") # This may raise a FileNotFoundError

except FileNotFoundError:

print("Error: File not found.")

The `finally` Block

In addition to `try` and `except`, you can include a `finally` block. Code within the `finally`

block always executes, regardless of whether an exception was raised or not. It is commonly

used to perform cleanup operations, such as closing files or network connections.

try:

# Code that may raise exceptions

except ExceptionType:

# Handle the exception

finally:

# Code that always executes

Example: Using `finally`

try:

file = open("sample.txt", "r")

content = file.read()

except FileNotFoundError:

print("Error: File not found.")

finally:

file.close() # Close the file, even if an exception occurred or not.

 

 

Built-in exceptions in Python

S. No

Name of the Built-in Exception

Explanation

1.

SyntaxError

It is raised when there is an error in the syntax of the Python code.

2.

ValueError

It is raised when a built-in method or operation receives an argument that has the right data type but mismatched or inappropriate values.

3.

IOError

It is raised when the file specified in a program statement cannot be opened.

4

KeyboardInterrupt

It is raised when the user accidentally hits the Delete or Esc key while executing a program due to which the normal flow of the program is interrupted.

5

ImportError

It is raised when the requested module definition is not found.

6

EOFError

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

7

ZeroDivisionError

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

8

IndexError

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

9

NameError

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

10

IndentationError

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

11

TypeError

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

12

OverFlowError

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

Program 1 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 2: Use of multiple except clauses

print ("Handling multiple exceptions")

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 3: 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...except…else clause

We can put an optional else clause along with the try...except clause. An except block will be executed only if some exception is raised in the try block. But if there is no error then none of the except blocks will be executed. In this case, the statements inside the else clause will be executed.

Program 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

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. It is a common practice to use finally clause while working with files to ensure that the file object is closed. If used, finally should always be placed at the end of try clause, after all except blocks and the else block.

Program 6: Use of finally clause

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

Question 1: Perfect division function

Write a function division() that accepts two arguments. The function should be able to catch an exception such as ZeroDivisionError.

Source code:

def division(x,y):

    try:

        div = x/y

        print(x,"/",y," = ",div)

    except ZeroDivisionError as e:

        print("Exception occurred!:", e)

    except Exception as e:

        print("Exception occurred!:", e)

a = int(input("Enter number a: "))

b = int(input("Enter number b: "))

division(a,b)

Example of IndexError

Code/Output

# lists
x = [1, 2, 3, 4]
try:
    print(x[10])
except IndexError as e:
    print(e)
# strings
x = "Pylenin"
try:
    print(x[10])
except IndexError as e:
    print(e)
# tuples
x = (1, 2, 3, 4)
try:
    print(x[10])
except IndexError as e:
    print(e)

Example of IndexError

print("Lets Try to find out the result for students in the class")

n=int(input("Enter the index number as roll number"))

try:

    marks_list = [20,30,50,80,90]

    print("Marks for roll no " + str(n) +" is " +str(marks_list[n]))

except IndexError as e:

    print("Student with roll no "+str(n)+" does not exist")

    print(e)

Example of TypeError

try:

    A=int(input("Enter a First Number :"))

    B=input("Enter a Second Number")

    C=A+B

    print("Sum=",C)

except TypeError as e:

    print("Both variables are not same data type")

Example Value Error

try:

      A=int(input("Enter a First Number :"))

      B=input("Enter a Second Number")

      C=A+Z

      print("Sum=",C)

except NameError as e:

      print("One variables is not defined")


No comments:

Post a Comment