Nearby lessons

84 of 159

Python - Raise Exception

📌 What You Will Learn
  • Distinguish predefined (built-in) exceptions from user-defined exceptions
  • Understand that Python raises predefined exceptions automatically
  • Define a custom exception class by extending the Exception class
  • Raise a customized exception explicitly using the raise keyword
  • Trace how different inputs lead to different outcomes in a raise-based program

Types of Exceptions

In Python, there are 2 types of exceptions.

  1. Predefined Exceptions
  2. User Defined Exceptions

1. Predefined Exceptions

Predefined Exceptions are also known as In-built Exceptions.

These exceptions are raised automatically by the Python Virtual Machine (PVM) whenever a particular event occurs.

Example 1

Whenever we try to perform division by zero, Python automatically raises a ZeroDivisionError.

🐍Code Cell
1print(10/0)
Output
ZeroDivisionError: division by zero

Example 2

Whenever we try to convert a non-integer value into an integer, Python automatically raises a ValueError.

🐍Code Cell
1x = int("ten")
Output
ValueError: invalid literal for int() with base 10: 'ten'

Summary of Predefined Exceptions

  • Raised automatically by Python.
  • Also called In-built Exceptions.
  • No need to create these exceptions manually.

2. User Defined Exceptions

User Defined Exceptions are also known as:

  • Customized Exceptions
  • Programmatic Exceptions

Sometimes we have to define and raise exceptions explicitly to indicate that something has gone wrong.

Python does not have any idea about these exceptions, so the programmer is responsible for defining them.

We have to raise them explicitly based on our requirement by using the raise keyword.

Examples of User Defined Exceptions

  • InSufficientFundsException
  • InvalidInputException
  • TooYoungException
  • TooOldException

Comparison

Predefined Exceptions User Defined Exceptions
Raised automatically by Python. Created by the programmer.
Also called In-built Exceptions. Also called Customized or Programmatic Exceptions.
No need to define them. Must be defined explicitly.
Raised automatically by the PVM. Raised manually by using the raise keyword.

How to Define and Raise Customized Exceptions

Every exception in Python is a class that extends the Exception class either directly or indirectly.

🐍Code Cell
1class ClassName(PredefinedExceptionClass):
2 def __init__(self, arg):
3 self.msg = arg
Output
No output captured.

Example

🐍Code Cell
1class TooYoungException(Exception):
2 def __init__(self, arg):
3 self.msg = arg
Output
No output captured.

Explanation

Here, TooYoungException is our class name, and it is a child class of Exception.

Raising a Customized Exception

We can raise a customized exception by using the raise keyword.

🐍Code Cell
1raise TooYoungException("message")
Output
No output captured.

Complete Example

🐍Code Cell
1class TooYoungException(Exception):
2 def __init__(self, arg):
3 self.msg = arg
4 
5class TooOldException(Exception):
6 def __init__(self, arg):
7 self.msg = arg
8 
9age = int(input("Enter Age:"))
10 
11if age > 60:
12 raise TooYoungException(
13 "Plz wait some more time you will get best match soon!!!"
14 )
15 
16elif age < 18:
17 raise TooOldException(
18 "Your age already crossed marriage age...no chance of getting marriage"
19 )
20 
21else:
22 print("You will get match details soon by email!!!")
Output
No output captured.

Output 1 - Age 90

D:\Python_classes>py test.py

Enter Age: 90

__main__.TooYoungException:

Plz wait some more time you will get best match soon!!!

Output 2 - Age 12

D:\Python_classes>py test.py

Enter Age: 12

__main__.TooOldException:

Your age already crossed marriage age...no chance of getting marriage

Output 3 - Age 27

D:\Python_classes>py test.py

Enter Age: 27

You will get match details soon by email!!!

Explanation

  • Age 90: since 90 > 60, the condition if age > 60 is true, so a TooYoungException is raised.
  • Age 12: since 12 < 18, the condition elif age < 18 is true, so a TooOldException is raised.
  • Age 27: neither condition is true, so the else block prints the success message.

Important Note

The raise keyword is best suitable for customized exceptions, but not for predefined exceptions.

📝 Key Takeaways
  • Predefined exceptions are raised automatically by the Python Virtual Machine (PVM)
  • User-defined exceptions are classes that extend Exception and are raised explicitly
  • The raise keyword is best suited for custom exceptions, not predefined ones
  • A raised custom exception stops the program unless it is handled elsewhere
  • An exception class can carry an extra message attribute set in __init__

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8