CBSERanker

Loading

Exception Handling in Python

Exception Handling in Python

“Handling the runtime errors”

What are Exceptions?

  • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
  • These exceptions can occur for various reasons, such as invalid user input, file not found, or division by zero.

Handling Exceptions

  • It is a powerful mechanism to handle runtime errors so that the normal flow of the application can be maintained.
  • Since exceptions abnormally terminate the execution of a program, it is important to handle them. In Python, we use try and except blocks to handle exceptions. Another keyword, finally, can also be used to perform cleanup tasks.

try block

  • The try block lets you test a block of code for errors.
  • We put all code inside the try block that may raise runtime errors.
  • When the try block encounters any runtime error, the control is passed to the appropriate except block.

except block

  • The except block lets you handle runtime errors.
  • When any runtime error occurs in the try block, the control is transferred to the except block to handle and maintain the normal execution of the program.
  • A default “except” block can handle any type of runtime error. However, we can pass the name of a specific runtime error with the except block to handle only that type of error.

Examples

Example 1: Handling Divide by Zero (Without try-except)

a = int(input('Enter First Number (A)'))
b = int(input('Enter Second Number (B)'))
c = a / b
print(c)
  • If the denominator is 0, the program crashes with a “ZeroDivisionError.”

Example 2: Handling Divide by Zero (With try-except)

try:
    a = int(input('Enter First Number (A)'))
    b = int(input('Enter Second Number (B)'))
    c = a / b
    print(c)
except:
    print('Sorry you cannot divide by zero')
  • If the denominator is 0, the program handles the error gracefully.

Example 3: Handling Specific Exception (ZeroDivisionError)

try:
    a = int(input('Enter First Number (A) '))
    b = int(input('Enter Second Number (B) '))
    c = a / b
    print(c)
except ZeroDivisionError:
    print('Sorry you cannot divide number by zero')
  • Only handles “ZeroDivisionError.” Other errors, like “ValueError,” will crash the program.

Example 4: Multiple Exception Handling

try:
    a = int(input('Enter First Number (A) '))
    b = int(input('Enter Second Number (B) '))
    c = a / b
    print(c)
    if a < b:
        d = d + a  # This will raise a NameError
        print(d)
except ZeroDivisionError:
    print('Sorry you cannot divide number by zero')
except ValueError:
    print('Please enter numbers only')
except:
    print('--Something went wrong--')
  • Handles multiple exceptions, including “ZeroDivisionError,” “ValueError,” and a default case for other errors.

finally block

  • The ‘finally’ block is always executed, whether an exception occurs or not.
  • It is used for cleanup actions like releasing resources or closing files.

Example with finally block:

try:
    a = int(input('Enter First Number (A) '))
    b = int(input('Enter Second Number (B) '))
    c = a / b
except ZeroDivisionError:
    print('Sorry you cannot divide number by zero')
except ValueError:
    print('Please enter numbers only')
except:
    print('--Something went wrong--')
finally:
    print('-- Thanks for using the code --')
  • The finally block executes in all cases, whether an exception occurs or not.

Points to Remember

  • The try block must be followed by either an except or finally block.
  • The except block is not mandatory with the try block, but it is necessary to handle errors for successful program execution.
  • While handling multiple exceptions, the default except block must be the last block; otherwise, a syntax error will occur with the message “default except must be last.”