Monday, June 8, 2026

4.5 ERROR HANDLING IN PYTHON

 DOWNLOAD PDF

4.5 ERROR HANDLING IN PYTHON

Error Handling

Error handling in Python is the process of detecting and handling errors during program execution using try, except, else, and finally blocks so that the program does not stop suddenly.

 

Errors and Exceptions

 

Errors

An error is a problem in a program that prevents the program from completing its task properly.

Errors may occur due to wrong syntax, incorrect logic, or invalid operations.

 

Debugging

Debugging is the process of finding and correcting errors or bugs in a program.

 

Types of Errors

There are mainly three types of errors in Python.

1.      Syntax Errors

2.      Runtime Errors / Exceptions

3.      Logical Errors

 

1. Syntax Error

A syntax error is an error that occurs when the rules of Python syntax are violated while writing a program.

Syntax errors are detected before the program executes.

 

Causes of Syntax Error

·         Missing colon :

·         Missing brackets

·         Wrong indentation

·         Spelling mistakes in keywords

 

Example

if 5 > 2
    print("Hello")

 

Error

SyntaxError

 

2. Runtime Error / Exception

A runtime error is an error that occurs during the execution of a program after it has been successfully compiled.

An exception is a runtime error that interrupts the normal flow of a program.

 

Causes of Runtime Error

·         Division by zero

·         Invalid input

·         Accessing invalid index

·         File not found

 

Example

a = 10 / 0

Error

ZeroDivisionError

3. Logical Error

A logical error is an error in which the program runs successfully but produces incorrect output.

Logical errors are difficult to detect because no error message is shown.

 

Example

a = 5
b = 3
 
print(a - b)

Expected addition was intended, but subtraction was used.

 

Exception Handling

Exception handling is the process of handling errors in a program using try, except, else, and finally blocks to prevent the program from stopping unexpectedly.

 

Components of Exception Handling

1.      try Block

2.      except Block

3.      else Block

4.      finally Block

 

1. try Block

A try block is a block used to test a block of code for errors.

If an exception occurs, Python immediately transfers control to the except block.

 

Syntax

try:
    # risky code

 

Important Points

·         Used for code that may generate errors

·         Prevents sudden program crash

·         Must be followed by except or finally block

 

2. except Block

The except block is a block used to handle errors or exceptions that occur in the try block.

 

Syntax

except:
    # handling code

 

Important Points

·         Executes only when an error occurs

·         Prevents abnormal termination of program

·         Can handle specific exceptions

 

Example

try:
    a = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Output

Cannot divide by zero

 

3. else Block

The else block is a block that executes only when no exception occurs in the try block.

The else block is optional and must come after all except blocks.

 

Syntax

else:
    # code if no error occurs

 

Example

try:
    a = 10 / 2
except ZeroDivisionError:
    print("Error")
else:
    print(a)

 

Output

5.0

 

4. finally Block

The finally block is a block that always executes whether an exception occurs or not.

It is mainly used for cleanup tasks such as closing files, releasing resources, or ending database connections.

 

Syntax

finally:
    # cleanup code

 

Example

try:
    a = 10 / 0
except:
    print("Error")
finally:
    print("Program Ended")

 

Output

Error
Program Ended

 

Complete Example of Exception Handling

try:
    numerator = int(input("Enter numerator: "))
    denominator = int(input("Enter denominator: "))
 
    result = numerator / denominator
 
except ZeroDivisionError:
    print("Cannot divide by zero")
 
else:
    print("Result:", result)
 
finally:
    print("Program execution completed")

 

Output

Enter numerator: 10
Enter denominator: 0
Cannot divide by zero
Program execution completed

 

Advantages of Exception Handling

1.      Prevents program crash

2.      Improves program reliability

3.      Makes debugging easier

4.      Provides better user experience

5.      Handles errors gracefully

 

Disadvantages of Exception Handling

1.      Increases code length

2.      Slightly slows program execution

3.      Difficult for beginners

4.      Improper handling may hide actual errors

 

Main Types of Exceptions in Python

 

1. ZeroDivisionError

ZeroDivisionError occurs when a number is divided by zero.

Example

a = 10 / 0

2. NameError

NameError occurs when a variable or function name is incorrect or undefined.

Example

print(name)

3. TypeError

TypeError occurs when incompatible data types are used together.

Example

a = "5" + 2

4. ValueError

ValueError occurs when the correct type of data is used but with an invalid value.

Example

num = int("abc")

5. IndexError

IndexError occurs when an invalid index is used in a list or sequence.

Example

list1 = [1, 2, 3]
 
print(list1[5])

 

6. FileNotFoundError

FileNotFoundError occurs when a file being opened does not exist.

Example

open("data.txt")

7. Exception as e

Exception as e is used to capture the actual error object and display the error message.


Example

try:
    a = 10 / 0
except Exception as e:
    print(e)

Output

division by zero

 

Common Exam Mistakes

❌ Writing expect instead of except
❌ Forgetting colon : after try and except
❌ Wrong indentation
❌ Confusing syntax error and logical error
❌ Forgetting that finally always executes

 

No comments:

Post a Comment