Exception Handling - CameronAuler/python-devops GitHub Wiki

Table of Contents

Try, Except, Else, and Finally Blocks

try-except Block

Python provides the try-except block to catch and handle exceptions.

try:
    result = 10 / 0  # This will cause an error
except ZeroDivisionError:
    print("Error: Division by zero is not allowed.")
# Output:
Error: Division by zero is not allowed.

Handling Multiple Exceptions

You can handle multiple exceptions using multiple except blocks.

try:
    num = int("abc")  # This will cause ValueError
except ZeroDivisionError:
    print("Error: Division by zero.")
except ValueError:
    print("Error: Invalid number format.")
# Output:
Error: Invalid number format.

else Block

The else block executes only if no exception occurs.

try:
    num = int("10")
    print("Conversion successful!")
except ValueError:
    print("Error: Invalid number format.")
else:
    print("No errors occurred.")
# Output:
Conversion successful!
No errors occurred.

finally Block

The finally block always executes, whether an exception occurs or not.

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("Error: File not found.")
finally:
    print("Closing the file.")
    file.close()
# Output:
Error: File not found.
Closing the file.

Raising Exceptions

You can use the raise keyword to manually trigger exceptions.

Raising a Built-in Exception

num = -5
if num < 0:
    raise ValueError("Negative numbers are not allowed.")
# Output:
ValueError: Negative numbers are not allowed.

Using raise Inside a try-except

try:
    raise ZeroDivisionError("This is a manually raised exception.")
except ZeroDivisionError as e:
    print(f"Caught an exception: {e}")
# Output:
Caught an exception: This is a manually raised exception.

Creating Custom Exceptions

Python allows creating custom exceptions by subclassing Exception.

Defining a Custom Exception

class NegativeNumberError(Exception):
    def __init__(self, message="Negative numbers are not allowed."):
        self.message = message
        super().__init__(self.message)

Using a Custom Exception

def check_number(num):
    if num < 0:
        raise NegativeNumberError()
    else:
        print("Valid number:", num)

try:
    check_number(-3)
except NegativeNumberError as e:
    print(f"Error: {e}")
# Output:
Error: Negative numbers are not allowed.

Types of Exceptions (Errors)

An exception is an error that occurs during execution. If not handled, the program will terminate.

Exception Description
ArithmeticError Base class for arithmetic-related exceptions.
AssertionError Raised when an assert statement fails.
AttributeError Raised when an invalid attribute reference occurs.
BaseException Base class for all built-in exceptions.
BufferError Raised when an operation cannot be performed on a buffer.
BytesWarning Raised as a warning related to bytes and bytearray operations.
DeprecationWarning Raised when deprecated features are used.
EOFError Raised when the input() function reaches the end of a file without reading any data.
EncodingWarning Raised when a default encoding warning occurs.
EnvironmentError Alias for OSError, raised for OS-related failures.
Exception Base class for all non-exiting exceptions.
FileExistsError Raised when trying to create a file that already exists.
FileNotFoundError Raised when trying to open a file that does not exist.
FloatingPointError Raised when a floating-point operation fails.
FutureWarning Raised for deprecated features that will be removed in the future.
GeneratorExit Raised when a generator is closed using close().
ImportError Raised when an imported module cannot be found.
ImportWarning Raised as a warning for potential import issues.
IndentationError Raised when incorrect indentation occurs.
IndexError Raised when trying to access an index that does not exist in a sequence.
InterruptedError Raised when an operation is interrupted by an external signal.
IsADirectoryError Raised when a file operation is attempted on a directory.
KeyError Raised when trying to access a non-existent key in a dictionary.
KeyboardInterrupt Raised when the user interrupts execution with Ctrl+C.
LookupError Base class for errors raised when a lookup operation fails.
MemoryError Raised when an operation runs out of memory.
ModuleNotFoundError Raised when trying to import a module that is not found.
NameError Raised when using a variable that has not been defined.
NotADirectoryError Raised when a directory operation is attempted on a file.
NotImplementedError Raised when an abstract method is not implemented in a subclass.
OSError Raised for operating system-related errors.
OverflowError Raised when an arithmetic operation exceeds the maximum limit.
PendingDeprecationWarning Raised for features that may be deprecated in future releases.
PermissionError Raised when an operation lacks the necessary permissions.
ProcessLookupError Raised when a process cannot be found.
RecursionError Raised when the maximum recursion depth is exceeded.
ReferenceError Raised when a weak reference object is accessed after garbage collection.
ResourceWarning Raised when resource cleanup warnings occur.
RuntimeError Raised when an error occurs that does not fit into other categories.
RuntimeWarning Raised as a warning related to runtime operations.
StopAsyncIteration Raised to signal the end of an asynchronous iterator.
StopIteration Raised to signal the end of an iterator.
SyntaxError Raised when a syntax error occurs.
SyntaxWarning Raised as a warning related to syntax issues.
SystemError Raised when an internal Python error occurs.
SystemExit Raised when sys.exit() is called.
TabError Raised when inconsistent indentation using tabs and spaces occurs.
TimeoutError Raised when an operation times out.
TypeError Raised when an operation is performed on an incorrect data type.
UnboundLocalError Raised when a local variable is accessed before assignment.
UnicodeDecodeError Raised when Unicode decoding fails.
UnicodeEncodeError Raised when Unicode encoding fails.
UnicodeError Raised for Unicode-related encoding and decoding errors.
UnicodeTranslateError Raised when a Unicode translation operation fails.
UserWarning Raised for user-generated warnings.
ValueError Raised when an operation receives an invalid value.
Warning Base class for warning-related exceptions.
ZeroDivisionError Raised when division by zero occurs.