Exception Handling in Python with Example

Exception Handling in Python :

  • Definition: Exception handling allows the program to catch and handle runtime errors without crashing. It is done using try, except, and optionally finally blocks.
  • Important Keywords: try, except, else, finally.

Types of Errors:

  1. Compile-time Error:
    • Definition: Occurs during code compilation before execution. Syntax errors, like misspelling a function, lead to compile-time errors.

    Example:

    print("heyy")
    printt("hey")  # Compile-time error: NameError because 'printt' is not defined
        
  2. Logical Error:
    • Definition: The code runs successfully but produces incorrect results due to a logic flaw in the program.

    Example:

    a = 10
    b = 30
    print(a + a)  # Logical error: Prints 40 instead of the expected result (10 + 30)
        
  3. Runtime Error:
    • Definition: Occurs while the program is running, usually due to invalid input, division by zero, etc.

    Example:

    a = int(input())
    b = int(input())
    print(a + b)  # Runtime error when input is not an integer (e.g., 'hiii')
        

Exception Handling with try and except:

Basic Exception Handling:

  • Definition: Catches any exception without specifying the type.

Example Program:

try:
    a = int(input())
    b = int(input())
    print(a + b)
except:
    print("Something went wrong")  # Catches all exceptions

Example Input:

10
20

Output:

Sum: 30

Post a Comment

0 Comments