The first method I learned for handling exceptions (errors) was using assert
to terminate the program when a condition wasn’t met.
This approach was particularly relevant when I was working on device drivers. In that environment, incorrect code could lead to severe issues like kernel panics, so exiting immediately made sense.
Later, when I moved on to other types of projects, I began using try
and except
(Python Document) blocks in Python. This method allowed for more graceful error handling, letting the program recover or provide useful feedback instead of abruptly exiting.
I believe handling exceptions is one of the key skills that separates learners from programmers. It’s a fundamental practice for application developers building reliable products, as it directly contributes to program stability.
In Python, we use try
and except
to prevent abrupt program termination by managing exceptions gracefully. This allows us to handle errors appropriately when they occur, ensuring the program can continue running or provide meaningful feedback to users.
Why use them
- Safely execute potentially error-prone code: Use
try
blocks to wrap code that might raise exceptions. - Perform alternative actions when an error occurs: Handle errors gracefully in the
except
block, providing fallback solutions or meaningful responses. - Ensure program continuity: Prevent crashes by managing exceptions, allowing your program to keep running smoothly.
Advantages
- Flexibility: Enables error contextualization by tailoring handling for specific exceptions.
- Readability: Clarifies the code structure, making error handling easier to understand.
- Reliability: Prevents unexpected program termination, ensuring a more robust execution.m.
Cons
- Risk of abuse: Ignoring or overusing predictable errors can complicate debugging and lead to overlooked issues.
- Poor performance:
try-except
blocks add a slight overhead, which can impact performance if overused in critical sections. - Lack of clarity: Failing to handle errors specifically can obscure underlying problems, making them harder to diagnose.
The disadvantages highlight why some developers are hesitant about handling exceptions. As a new programmer, I’ve often faced the frustration of trying to debug code that wasn’t working as expected, only to realize the issue was hidden by poorly implemented exception handling. This can make identifying and fixing bugs much more challenging.
Handling Exceptions Code
try:
print('Main code')
raise e
except Exception as e:
print('Exception code')
else: # Omitable
print('If no exception was thrown')
finally: # Omitable
print('Exception thrown or not, or both')
"""
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarning
"""
Python provides a wide range of built-in exception types, and while you don’t need to know all of them upfront, it’s important to set clear rules for handling exceptions as you get deeper into development. When working on a team, discussing and standardizing exception-handling practices ensures consistency and makes debugging easier for everyone.