Class 12 Computer Science - CBCS Curriculum
Detailed Topper Notes: Chapter 1 - Exception Handling in Python (Page 1 to 9)
1. Introduction
In any Python program, errors can arise due to three broad reasons:
1. Syntax Errors: Mistakes in code grammar.
2. Runtime Errors (Exceptions): Arise during execution.
3. Logical Errors: Valid code, but wrong results due to flawed logic.
Python has a built-in mechanism to handle runtime errors, known as exception handling. This
mechanism ensures the program does not crash unexpectedly and allows graceful management of
errors.
2. Syntax Errors
Definition: Occur when code violates Python's grammatical rules.
Also known as parsing errors.
Must be fixed before program execution.
Example:
if x == 5
print("Error") # SyntaxError: Missing colon
Errors in shell mode or script mode generate error messages highlighting the line and nature of the
syntax issue.
3. Exceptions
Even if syntax is correct, a program may encounter runtime errors during execution. These are
termed as exceptions.
Key Concepts:
- Exception is an object representing the error.
- It is raised when an error occurs during execution.
- Needs to be handled by the programmer.
Example:
print(10/0) # Raises ZeroDivisionError
SyntaxErrors are a type of exception, but most exceptions occur after successful parsing.
4. Built-in Exceptions
Python comes with a set of predefined exceptions to handle common error scenarios.
Table of common exceptions provided above.
5. Raising Exceptions
raise Statement
Used to manually throw an exception:
raise ValueError("Invalid input!")
assert Statement
Used for debugging or validating conditions.
assert x > 0, "OOPS... Negative Number"
Note: When an exception is raised, remaining statements in the block are skipped.
6. Handling Exceptions
Need for Exception Handling
- Keeps main logic separate from error handling.
- Prevents abnormal program termination.
- Helps handle both user-defined and built-in exceptions.
How It Works
1. When an error occurs, Python creates an exception object.
2. The runtime system searches for a matching exception handler (except block).
3. Search begins in the current function, then in the call stack.
4. If found, the exception is caught and handled.
5. If not found, the program stops execution.
7. try...except Block
Syntax:
try:
# code that may raise exception
except ExceptionName:
# handler code
Example:
try:
x = int(input("Enter a number: "))
print(10/x)
except ZeroDivisionError:
print("Cannot divide by zero!")
8. Multiple except Blocks
A single try block can have multiple except clauses.
Order matters.
Generic Except:
except:
print("Some exception occurred")
9. try...except...else Block
try:
# code
except:
# handle error
else:
# execute if no error
10. try...except...else...finally
try:
# code
except:
# error handling
else:
# if no error
finally:
# always executes
Example provided above with file handling.
Summary:
- Use raise to trigger exceptions.
- Use try...except to catch and handle them.
- Use assert for input validation.
- Use else for post-success logic.
- Use finally for cleanup.
---
End of Notes (Page 1 to 9)