CBSETest.comby Bimal Publications

Need help with Exception Handling in Python?

Practice Tests
Class 12 · Computer Science NCERT Class 12 Computer Science · Ch. 15 min read · 15 questions

Exception Handling in Python

Computer Science

Exception Handling in Python

When a Python program encounters an error during execution, it raises an exception — an event that disrupts the normal flow of the program. Without proper handling, the program simply crashes and prints a traceback. Exception handling allows us to anticipate errors, respond to them gracefully, and keep the program running or exit cleanly with a meaningful message.

Types of Errors in Python

Syntax Errors occur before execution when the interpreter cannot parse the code (missing colon, mismatched brackets). These are NOT exceptions.

Runtime Errors (Exceptions) occur during execution. Common built-in exceptions include:

| Exception | Cause |
|-----------|-------|
| ZeroDivisionError | Dividing a number by zero |
| ValueError | Passing an invalid value to a function |
| TypeError | Operation on incompatible types |
| IndexError | Accessing a list index out of range |
| KeyError | Accessing a missing dictionary key |
| FileNotFoundError | Opening a file that does not exist |
| NameError | Using a variable that has not been defined |
| OverflowError | Arithmetic result too large to represent |
| ImportError | Failing to import a module |

The try-except Block

The basic structure for handling exceptions:

```
try:
# code that might raise an exception
except ExceptionType:
# code to run if that exception occurs
```

Multiple except clauses handle different exception types separately. Python checks them top-to-bottom and executes the first matching clause.

The else and finally Clauses

else — runs if the try block completed WITHOUT raising any exception (useful for code that should only run on success).

finally — runs ALWAYS, whether or not an exception occurred. Ideal for cleanup tasks like closing files or releasing resources.

Structure:
```
try:
riskycode()
except ValueError:
handlevalueerror()
except ZeroDivisionError:
handlezerodiv()
else:
successcode()
finally:
cleanupcode()
```

Raising Exceptions

You can deliberately raise an exception using the raise statement:

```
raise ValueError('Age cannot be negative')
```

This is useful when your own validation logic detects an invalid state.

Exception Hierarchy

All built-in exceptions inherit from BaseException. Most user-visible exceptions inherit from Exception. Using a bare except: (no type) catches everything including system-exit signals — this is generally discouraged. Catching the broad Exception is sometimes acceptable but catching specific types is always preferred.

Worked Examples

Example 1 — ZeroDivisionError:
```
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero.')
```
Output: Cannot divide by zero.

Example 2 — Multiple exceptions:
```
try:
n = int(input('Enter a number: '))
print(100 / n)
except ValueError:
print('Please enter a valid integer.')
except ZeroDivisionError:
print('Zero is not allowed.')
```

Example 3 — finally for cleanup:
```
try:
f = open('data.txt', 'r')
content = f.read()
except FileNotFoundError:
print('File missing.')
finally:
print('Done.') # always prints
```

Common mistakes

  • Catching too broadly — using a bare `except:` hides all errors, making debugging very hard. Always specify the exception type.
  • Ignoring the exception — an empty except block silently swallows errors. At minimum, print or log the error.
  • Putting too much in try — only the statements that might raise an exception should be inside the try block.
  • Forgetting finally — file handles and database connections should always be closed; use finally or the with statement.

Summary

Exception handling makes programs robust. Use try to wrap risky code, except to catch specific errors, else for success-only logic, and finally for guaranteed cleanup. The raise statement lets you signal errors from your own code. Specific exception types should always be preferred over broad catches.

Practice Problems

15 questions with instant feedback.

Question 1 of 15Score 0

Which keyword is used in Python to catch an exception that has been raised?