ERRORS AND EXCEPTIONS
NKOSANA NXUMALO
241FA01089
BIOTECHNOLOGY
DEFINITIONS AND EXAMPLES
• Errors: Problems in a program that cause it to stop execution. They
can be categorized into:
• Syntax Errors: Occur when the code does not follow the correct syntax.
• Runtime Errors: Happen during execution, often due to invalid operations.
• Exceptions: Special conditions that change the normal flow of
execution. They can be handled using specific constructs in Python.
SYNTAX ERRORS
• Occur when the code is not written correctly.
• Example:
if x > 10
print("x is greater than 10") # Missing colon
RUNTIME ERRORS/LOGICAL ERRORS
• Occur during execution, such as dividing by zero or accessing an out-
of-bounds index.
• Example:
result = 10 / 0 # ZeroDivisionError
COMMON BUILT IN EXCEPTIONS
• BaseException: Base class for all exceptions.
• AttributeError: Invalid attribute reference.
• EOFError: input() hits end-of-file.
• FloatingPointError: Floating-point operation fails.
• ImportError: Module not found.
• IndexError: Sequence index out of range.
• KeyError: Dictionary key not found.
• KeyboardInterrupt: User interrupts (Ctrl+C).
• MemoryError: Operation runs out of memory.
• ZeroDivisionError: Division by zero.
Contie…..
NameError: Variable not found.
• OverflowError: Arithmetic result too large.
• RuntimeError: General error not categorized.
• SyntaxError: Parsing error.
• IndentationError: Incorrect indentation.
• TabError: Inconsistent tabs/spaces.
• SystemError: Internal interpreter error.
• SystemExit: Raised by sys.exit().
• TypeError: Invalid operation for type.
• ValueError: Correct type, wrong value.
Try and Except Blocks
• Used to catch and handle exceptions gracefully.
• Example:
try:
value = int(input("Enter a number: "))
except ValueError:
print("That's not a valid number!")
Else Bock
• Executes if the try block does not raise an exception.
• Example:
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result is:", result)
Finally Block
• Executes regardless of whether an exception occurred or not. Useful for
cleanup actions.
• Example:
try:
file = open("example.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
file.close() # Ensures the file is closed
Raising Exceptions
• You can raise exceptions intentionally using the raise keyword.
• Example:
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
User-defined Exceptions
• Custom exceptions can be created by inheriting from the built-in
Exception class.
• Example:
class CustomError(Exception):
pass
raise CustomError("This is a custom error message.")
APPLICATION IN REAL LIFE
• Financial Transactions:
• In banking systems, exceptions are crucial for managing scenarios like
insufficient funds or invalid account numbers. For example, if a user attempts
to withdraw more money than they have, an exception can be raised to
prevent the transaction and notify the user.
• Automated Systems:
• In automated systems like ATMs, error handling is essential. If the machine
runs out of cash or encounters a technical issue, it can raise exceptions to halt
operations and inform the user, ensuring that no erroneous transactions occur.

Mastering Errors and Exceptions in Python: A Comprehensive Guide

  • 1.
    ERRORS AND EXCEPTIONS NKOSANANXUMALO 241FA01089 BIOTECHNOLOGY
  • 2.
    DEFINITIONS AND EXAMPLES •Errors: Problems in a program that cause it to stop execution. They can be categorized into: • Syntax Errors: Occur when the code does not follow the correct syntax. • Runtime Errors: Happen during execution, often due to invalid operations. • Exceptions: Special conditions that change the normal flow of execution. They can be handled using specific constructs in Python.
  • 3.
    SYNTAX ERRORS • Occurwhen the code is not written correctly. • Example: if x > 10 print("x is greater than 10") # Missing colon
  • 4.
    RUNTIME ERRORS/LOGICAL ERRORS •Occur during execution, such as dividing by zero or accessing an out- of-bounds index. • Example: result = 10 / 0 # ZeroDivisionError
  • 5.
    COMMON BUILT INEXCEPTIONS • BaseException: Base class for all exceptions. • AttributeError: Invalid attribute reference. • EOFError: input() hits end-of-file. • FloatingPointError: Floating-point operation fails. • ImportError: Module not found. • IndexError: Sequence index out of range. • KeyError: Dictionary key not found. • KeyboardInterrupt: User interrupts (Ctrl+C). • MemoryError: Operation runs out of memory. • ZeroDivisionError: Division by zero.
  • 6.
    Contie….. NameError: Variable notfound. • OverflowError: Arithmetic result too large. • RuntimeError: General error not categorized. • SyntaxError: Parsing error. • IndentationError: Incorrect indentation. • TabError: Inconsistent tabs/spaces. • SystemError: Internal interpreter error. • SystemExit: Raised by sys.exit(). • TypeError: Invalid operation for type. • ValueError: Correct type, wrong value.
  • 7.
    Try and ExceptBlocks • Used to catch and handle exceptions gracefully. • Example: try: value = int(input("Enter a number: ")) except ValueError: print("That's not a valid number!")
  • 8.
    Else Bock • Executesif the try block does not raise an exception. • Example: try: result = 10 / 2 except ZeroDivisionError: print("Cannot divide by zero.") else: print("Result is:", result)
  • 9.
    Finally Block • Executesregardless of whether an exception occurred or not. Useful for cleanup actions. • Example: try: file = open("example.txt", "r") except FileNotFoundError: print("File not found.") finally: file.close() # Ensures the file is closed
  • 10.
    Raising Exceptions • Youcan raise exceptions intentionally using the raise keyword. • Example: def check_age(age): if age < 0: raise ValueError("Age cannot be negative.")
  • 11.
    User-defined Exceptions • Customexceptions can be created by inheriting from the built-in Exception class. • Example: class CustomError(Exception): pass raise CustomError("This is a custom error message.")
  • 12.
    APPLICATION IN REALLIFE • Financial Transactions: • In banking systems, exceptions are crucial for managing scenarios like insufficient funds or invalid account numbers. For example, if a user attempts to withdraw more money than they have, an exception can be raised to prevent the transaction and notify the user. • Automated Systems: • In automated systems like ATMs, error handling is essential. If the machine runs out of cash or encounters a technical issue, it can raise exceptions to halt operations and inform the user, ensuring that no erroneous transactions occur.