HomeComputer ScienceClass 12Chapter 9: Exception Handling

Exception Handling in Python

1. Board Exam Pattern

As Per CBSE Syllabus:

  • 3 Marks from this Chapter (Very Important)
  • Likely to have questions on try-except-finally blocks
  • Practical implementation of exception handling

2. What is an Exception?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of the program's execution. When Python encounters an error, it raises an exception.

2.1 Key Concepts:

  • Error: A mistake in the program that prevents it from running correctly
  • Exception: An error that occurs during execution (runtime error)
  • Exception Handling: Process of catching and handling exceptions gracefully
  • Without handling: Program crashes and terminates abruptly
  • With handling: Program continues executing even after an error

2.2 Example - Error without Handling:

# Program without exception handling
x = 10
y = 0
result = x / y  # ZeroDivisionError - Program CRASHES
print("Result:", result)

2.3 Example - Error with Handling:

# Program with exception handling
x = 10
y = 0
try:
    result = x / y
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
print("Program continues normally")  # Executes normally

3. Two Main Types of Errors

3.1 Syntax Errors (Compile-time Errors)

  • Occur when Python grammar rules are violated
  • Detected by the Python interpreter before execution
  • Program cannot run at all
  • Cannot be handled using try-except

Examples of Syntax Errors:

# Syntax Error 1: Missing colon
if x > 5
    print("x is greater than 5")

# Syntax Error 2: Incorrect indentation
if x > 5:
print("x is greater than 5")

# Syntax Error 3: Missing quotes
print(Hello World)

# Syntax Error 4: Wrong bracket
result = [1, 2, 3)  # Mixed brackets

3.2 Runtime Errors (Logical Errors)

  • Occur during program execution
  • Program starts running but crashes when error is encountered
  • Can be handled using try-except blocks
  • Also called Exceptions

Common Runtime Errors (Exceptions):

Exception TypeCauseExample
ZeroDivisionErrorDivision by zero10 / 0
ValueErrorInvalid value for operationint("abc")
TypeErrorWrong data type"string" + 5
IndexErrorIndex out of rangelist[10] (for list of 5 items)
KeyErrorDictionary key doesn't existdict["missing_key"]
NameErrorUndefined variableprint(undefined_var)
FileNotFoundErrorFile doesn't existopen("missing.txt")

4. Handling Exception in Python

Method 1: Try and Except Block

The basic structure for exception handling. The try block contains code that might cause an error. The except block handles the error if it occurs.

Syntax:

try:
    # Code that might cause an exception
    statement1
    statement2
except ExceptionType:
    # Code to handle the exception
    action1
    action2

Example 1 - ZeroDivisionError:

x = 10
y = 0

try:
    result = x / y
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
    result = 0

print("Result:", result)
print("Program continues normally")

Example 2 - ValueError:

try:
    num = int(input("Enter a number: "))
    print("You entered:", num)
except ValueError:
    print("Error: You must enter a valid number!")
    print("Non-numeric input detected")

Example 3 - IndexError:

my_list = [10, 20, 30]

try:
    print(my_list[5])  # Index 5 doesn't exist
except IndexError:
    print("Error: Index out of range!")
    print("List only has", len(my_list), "elements")

Method 2: Try-Except with Else Block

The else block executes if NO exception occurs in the try block. Used when you want to run code only if the try block is successful.

Syntax:

try:
    # Risky code
    statement1
except ExceptionType:
    # Handle exception
    action1
else:
    # Executes ONLY if no exception
    action2

Example:

x = 10
y = 2

try:
    result = x / y
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
else:
    print("Division successful!")
    print("Result:", result)  # Executes because no error

Method 3: Try with Multiple Except Blocks

Handle different types of exceptions differently. Each except block handles a specific exception type.

Syntax:

try:
    # Code that might cause different exceptions
    statement1
except ExceptionType1:
    # Handle first exception
    action1
except ExceptionType2:
    # Handle second exception
    action2
except ExceptionType3:
    # Handle third exception
    action3

Example 1 - Multiple Exception Types:

print("Simple Calculator")

try:
    x = int(input("Enter first number: "))
    y = int(input("Enter second number: "))
    result = x / y
except ValueError:
    print("Error: Please enter valid numbers!")
except ZeroDivisionError:
    print("Error: Cannot divide by zero!")
else:
    print("Result:", result)

Example 2 - List Access:

my_list = [10, 20, 30]

try:
    index = int(input("Enter index: "))
    value = my_list[index]
except ValueError:
    print("Error: Index must be a number!")
except IndexError:
    print("Error: Index out of range!")
else:
    print("Value at index:", value)

Example 3 - Catching All Exceptions:

try:
    # Some risky code
    result = x / y
except ValueError:
    print("Error: Invalid value")
except ZeroDivisionError:
    print("Error: Division by zero")
except Exception:
    # Catches ALL other exceptions
    print("An unknown error occurred!")

Method 4: Try-Except-Finally Block

The finally block ALWAYS executes, whether an exception occurs or not. Used for cleanup operations (closing files, releasing resources).

Syntax:

try:
    # Code that might cause exception
    statement1
except ExceptionType:
    # Handle exception
    action1
finally:
    # ALWAYS executes (with or without exception)
    cleanup_code

Example 1 - File Operations:

try:
    file = open("data.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("Error: File not found!")
finally:
    file.close()  # ALWAYS closes file
    print("File closed")

Example 2 - Resource Cleanup:

def divide(x, y):
    try:
        result = x / y
        return result
    except ZeroDivisionError:
        print("Error: Cannot divide by zero")
        return None
    finally:
        print("Division operation completed")
        # Always executes, even with return

print("Result:", divide(10, 2))
print("---")
print("Result:", divide(10, 0))

Example 3 - Complete Structure:

try:
    print("Trying...")
    x = int(input("Enter a number: "))
    result = 10 / x
except ValueError:
    print("ValueError: Enter a valid number!")
except ZeroDivisionError:
    print("ZeroDivisionError: Cannot divide by zero!")
else:
    print("Success! Result:", result)
finally:
    print("Finally block always executes!")
    print("Program cleanup completed")

Finally Block Key Points:

  • Executes whether exception occurs or not
  • Executes even if except block has a return statement
  • Used for cleanup: closing files, releasing resources, database connections
  • Cannot be skipped (except for system.exit() or os._exit())

5. Exception Handling Methods - Summary

MethodStructureUse Case
try-exceptBasic error handlingSimple exception catching
try-except-elseRun code on successExecute code only if no error
Multiple exceptDifferent handlersMultiple exception types
try-except-finallyAlways cleanupResource cleanup, file closing

6. Best Practices for Exception Handling

  • Catch specific exceptions: Avoid bare except. Always specify exception type
  • Don't ignore exceptions: Print error messages to help debugging
  • Use finally for cleanup: Always close files and release resources
  • Handle exceptions at appropriate level: Catch exceptions where they can be handled
  • Test exception handling: Test what happens when errors occur
  • Use meaningful error messages: Help users understand what went wrong
    Built with v0