Concept Flow - Common exception types
Start
Run code
Error occurs?
No→End
Yes
Identify exception type
Handle or show error
End
The program runs code, checks if an error happens, identifies the type of error, then handles or shows it before ending.
try: x = int('abc') except ValueError as e: print('ValueError:', e)
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Try to convert 'abc' to int | int('abc') | Raises ValueError |
| 2 | Catch ValueError exception | except ValueError as e | Exception caught |
| 3 | Print error message | print('ValueError:', e) | Output: ValueError: invalid literal for int() with base 10: 'abc' |
| 4 | End of try-except block | No more code | Program continues or ends |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| x | undefined | Exception raised, no value assigned | undefined | undefined |
| e | undefined | undefined | ValueError instance | ValueError instance |
Common exceptions in Python include ValueError, TypeError, ZeroDivisionError, and KeyError. Use try-except blocks to catch and handle exceptions. The except block must match the exception type to catch it. Catching exceptions prevents program crashes and allows graceful error handling.