Introduction

  • Exception handling is an OOPs concept of Python.

Definition

  • An exception is an error that occurs during program execution or run time.

Characteristics

  • Exception handling in Python is a mechanism used to handle runtime errors (exceptions) so that the normal flow of a program is not interrupted. Instead of crashing, the program can respond gracefully by handling an exception.

Advantages or Need of Exception Handling

  • It prevents abnormal program crashes or termination.
  • It improves program reliability.
  • It separates error-handling code from normal code.
  • It helps in debugging and maintenance.
  • It improves program robustness.
  • It helps in error recovery.
  • It makes code cleaner and more readable.

Elements of Exception Handling

  • Exception handling in Python uses try, except, else, finally, and raise keywords to manage runtime errors effectively, ensuring smooth program execution.
  • The following major elements are used to catch and handle exceptions that arise suddenly.
    • try block
    • except block
    • else block
      • This block is used mainly when no exception occurs. eg- 
try:
    x = int(input(“Enter number: “))
    print(10 / x)
except ZeroDivisionError:
    print(“Zero is not allowed”)
else:
    print(“Execution successful”)
    • raise block
      • This block is used to raise custom or predefined exceptions.
      • For example –
age = int(input(“Enter your age: “))
if age < 18:
    raise ValueError(“Age must be 18 or above”)
    • finally block
      • This block is used to execute whether an exception occurs or not.
      • It is used for cleanup operations. 
      • For example –
try:
    file1 = open(“data.txt”, “r”)
    print(file1.read())
except FileNotFoundError:
    print(“File not found”)
finally:
    file1.close()
    print(“Closing the file”)
    • User-Defined (Custom) Exceptions
      • This exception type is used to create our own or customized exception class.
      • For example –
class MyException(Exception):
    pass
try:
    num = int(input(“Enter a number: “))
    if num < 0:
        raise MyException(“Negative number not allowed”)
exceptMyException as e:
    print(e)
Here, MyException is a user-defined class name, and it may also be any name, and Exception is a built-in base class.

Syntax

try:
    # codes that may cause exceptions
except ExceptionType:
    # code to handle exception
NB: We can also catch all exceptions (but it’s not recommended for large programs) using an except block without specifying an exception type. e.g.-
try:
    x = int(“Welcome”)
except:
    print(“An error occurred”)

Example

try:
    a = int(input(“Enter a number: “))
    b = 10 / a
    print(b)
except ZeroDivisionError:
    print(“Division by zero is not allowed”)

Built-in Exceptions in Python

Some common Built-in Exceptions of Python are –

          Exception Type Name     –     Description

  • ZeroDivisionError   –    Division by zero
  • ValueError  –    Invalid value
  • TypeError   –    Wrong data type
  • IndexError  –    Index out of range
  • KeyError    –     Dictionary key missing
  • FileNotFoundError   –    File not found

=======================  XXX  ========================

Program Examples on Exception Handling

Example: A Python program to handle multiple exceptions.
try:
    x = int(input("Enter First Number: "))
    y = int(input("Enter Second Number: "))
    print(x / y)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid input! Enter integers only")

Loading

Categories: Python Theory

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.