Computer Science

Exception Handling in Python Class 12 CBSE (083): try, except and finally with Examples

Class 12 · Computer Science

Exception Handling in Python (CBSE Class 12 Computer Science - 083)

While writing Python programs, errors may occur due to invalid input, incorrect calculations, missing files, or other unexpected situations. If these errors are not handled properly, the program terminates abruptly. Exception Handling allows programmers to handle such errors gracefully without crashing the program.

Learning Objectives

  • Understand the concept of exceptions.
  • Differentiate between syntax errors and exceptions.
  • Learn the importance of exception handling.
  • Use try, except, and finally blocks.
  • Write robust Python programs that handle runtime errors.

What is an Exception?

An exception is a runtime error that occurs while executing a program. When an exception occurs, Python stops the normal execution of the program and displays an error message unless the exception is handled.

Definition: An exception is an event that interrupts the normal flow of a program during execution.

Why Do We Need Exception Handling?

Exception handling helps to:

  • Prevent program crashes.
  • Display meaningful error messages.
  • Continue program execution even after an error.
  • Improve the reliability of programs.
  • Provide a better user experience.

Errors vs Exceptions

Syntax Error Exception
Occurs due to incorrect Python syntax. Occurs during program execution.
Program cannot start. Program starts but stops when the error occurs.
Must be corrected before execution. Can be handled using exception handling.

Example of Syntax Error


print("Hello"

Example of Exception


num = 10
print(num/0)

Output


ZeroDivisionError: division by zero

Common Exceptions in Python

Exception Cause
ZeroDivisionError Division by zero.
ValueError Invalid value entered.
TypeError Operation performed on incompatible data types.
NameError Using an undefined variable.
IndexError Accessing an invalid list index.
KeyError Accessing a missing dictionary key.
FileNotFoundError Specified file does not exist.

Exception Handling

Python provides the try, except, and finally blocks to handle exceptions effectively.


The try Block

The code that may generate an exception is placed inside the try block.

Syntax


try:
    statements

The except Block

If an exception occurs inside the try block, Python transfers control to the except block.

Syntax


try:
    statements
except:
    statements

Example 1: Handling ZeroDivisionError


try:
    num = 20
    print(num/0)

except:
    print("Division by zero is not allowed.")

Output


Division by zero is not allowed.

Example 2: Handling ValueError


try:
    age = int(input("Enter Age : "))
    print(age)

except:
    print("Please enter a valid integer.")

Handling Specific Exceptions

Instead of handling all exceptions together, Python allows us to handle a particular exception separately.

Syntax


try:
    statements

except ExceptionName:
    statements

Example


try:
    number = int(input("Enter Number : "))
    print(100/number)

except ZeroDivisionError:
    print("Cannot divide by zero.")

except ValueError:
    print("Please enter a valid integer.")

Multiple except Blocks

A single try block can have multiple except blocks to handle different types of exceptions.


try:
    a = int(input("Enter First Number : "))
    b = int(input("Enter Second Number : "))
    print(a/b)

except ValueError:
    print("Invalid Input")

except ZeroDivisionError:
    print("Division by zero is not possible.")

The finally Block

The finally block always executes whether an exception occurs or not. It is generally used to release resources such as closing files or database connections.

Syntax


try:
    statements

except:
    statements

finally:
    statements

Example: try-except-finally


try:
    number = int(input("Enter Number : "))
    print(100/number)

except ZeroDivisionError:
    print("Division by zero is not allowed.")

except ValueError:
    print("Please enter a valid integer.")

finally:
    print("Program Finished.")

Possible Output (Input: 5)


20.0
Program Finished.

Possible Output (Input: 0)


Division by zero is not allowed.
Program Finished.

Flow of Exception Handling

  1. Python executes the statements inside the try block.
  2. If no exception occurs, the except block is skipped.
  3. If an exception occurs, the corresponding except block executes.
  4. The finally block always executes before the program ends.

Advantages of Exception Handling

  • Prevents abnormal program termination.
  • Improves program reliability.
  • Makes programs user-friendly.
  • Separates error-handling code from normal code.
  • Helps in debugging and maintenance.

Common Programming Mistakes

  • Using try without an except or finally block.
  • Placing unrelated statements inside the try block.
  • Ignoring specific exceptions when they can be handled separately.
  • Writing code after an exception without proper handling.

Exam Tips

  • Remember that exceptions are runtime errors.
  • The try block contains code that may generate an exception.
  • The except block handles the exception.
  • The finally block always executes, regardless of whether an exception occurs.
  • Practice programs involving ZeroDivisionError and ValueError, as they are commonly asked in CBSE examinations.

Frequently Asked Questions (FAQs)

1. What is an exception?

An exception is a runtime error that interrupts the normal execution of a program.

2. Why is exception handling important?

It prevents program crashes and allows the program to continue executing gracefully.

3. What is the purpose of the try block?

The try block contains the code that may generate an exception.

4. What is the purpose of the except block?

The except block handles the exception if one occurs in the try block.

5. When is the finally block executed?

The finally block is executed in every case, whether an exception occurs or not.


Summary

  • An exception is a runtime error that interrupts the normal flow of a program.
  • Exception handling makes programs more reliable and user-friendly.
  • The try block contains code that may raise an exception.
  • The except block handles the exception and prevents abrupt program termination.
  • Multiple except blocks can be used to handle different exceptions.
  • The finally block always executes and is commonly used for cleanup tasks.
  • Common exceptions include ZeroDivisionError, ValueError, TypeError, NameError, and FileNotFoundError.