Introduction

In Python, raising exceptions is an important aspect of error handling. Exception handling enables programmers to identify and deal with errors that may occur during the execution of their code. Exception handling in Python can be achieved by explicitly raising exceptions using the raise statement. This allows programmers to create custom exceptions and messages that provide more information about the nature of the error.  In this tutorial, we will explore the concept of raising exceptions in Python and learn how to implement it in our projects.

Table of Contents :

  • Exception raising by python interpreter
  • Manually raising Exceptions in Python
    • Using Exception classes while raising exception

Exception raising by python interpreter :

  • Python exceptions are errors that occur during the execution of a program. 
  • Exceptions are raised when a program encounters an error condition during execution. 
  • When an exception is raised, the Python interpreter stops the execution of the program and displays an error message. 
  • We have already seen how python handles exceptions using try...except construct, try..except..finally construct and try..except..else construct.
  • So far in the section of exception handling in python, we have seen scenarios where the exceptions were raised internally by the python interpreter itself. But in python we can raise exceptions manually as well at our will.

Manually raising Exceptions in Python

  • While writing python code, at times we might want to raise an exception or throw an exception manually if a certain condition is met.
  • There may scenarios where certain values of user input do not fit right in out logic. In such scenarios we can explicitly raise an exception.
  • Exceptions can be raised manually by using the raise keyword. 
  • The syntax of raising an exception is :  raise Exception("An error has occurred") 
  •  Code Sample : A simple code sample of raising exception is :

def show_details(name, id):
    try:
        print("Inside try block")
        if id < 0:
            raise Exception("Id should be a Positive number.")
        else:
            print(f"The name is : {name}")
            print(f"The id is : {id}")
    except Exception as e:
        print("Inside except block : ", e)


show_details("John", -5)
print()
show_details("Alice", 1)


# Output
# Inside try block
# Inside except block :  Id should be a Positive number.

# Inside try block
# The name is : Alice
# The id is : 1

  
  

Using Exception classes while raising exception :

  • Exceptions can also be raised by using the  raise  keyword with an instance of an  Exception  class. 
  • For example, this code raises a  ValueError  exception :  raise ValueError("Invalid input") 
  • Code Sample :

def divide(numerator, denominator):
    try:
        print("Inside try block")
        if denominator == 0:
            raise ZeroDivisionError("Sorry, Denominator cannot be zero.")
        else:
            d = numerator / denominator
            print(f"The value of quotient is {d}")
    except ZeroDivisionError as e:
        print("Inside except block : ", e)


divide(20, 0)
print()
divide(20, 4)

# Output
# Inside try block
# Inside except block :  Sorry, Denominator cannot be zero.

# Inside try block
# The value of quotient is 5.0


  
  

Prev. Tutorial : Try..except..else

Next Tutorial : Built-in exceptions