Exception is everywhere in Python. Virtually every module in the standard Python library uses them, and Python itself will raise them in a lot of different circumstances. Here are just a few examples:
⦁ Accessing a non-existent dictionary key will raise a key error exception.
⦁ Searching a list for a non-existent value will raise a ValueError exception.
⦁ Calling a non-existent method will raise an AttributeError exception.
⦁ Referencing a non-existent variable will raise a NameError exception.
⦁ Mixing datatypes without coercion will raise a TypeError exception.
1.Example for Exception:
a = int(input("Enter a:")) b = int(input("Enter b:")) c = a/b; print("a/b = %d"%c) #other code: print("Hi I am other part of the program") Output: Enter a:10 Enter b:0 Traceback (most recent call last): File "exception-test.py", line 3, in <module> c = a/b; ZeroDivisionError: division by zero
Making your own exceptions involves object-oriented-programming, To make a custom exception, the programmer determines which base exception to use as the class to inherit from, e.g. making an exception for negative numbers or one for imaginary numbers
Defining custom exception:
import math #neccessary for square root function
“””Attempted improper operation on negative number”””.
“Computes the square root of a number. Raises NegativeNumberError
if the number is less than 0.”
if number< 0:
“Square root of negative number not permitted”
The first line creates the custom exception NegativeNumberError, which inherits from ArithmeticError.Because it inherits all the features of the base exception, you don’t have to define anything else, hence the pass statement that signifies that no actions are to be performed. Then, to use the new exception, a function is created (square root()) that calls NegativeNumberError if the argument value is less than 0,otherwise, it gives the square root of the number.