In this post, we will learn about raise keyword in Python with detailed explanation and examples. so let’s start learning…

raise keyword

raise keyword is used to raise custom exceptions in Python. it will allow you to raise exceptions or errors in your program according to specified conditions and also print custom message that will help in debugging.

Syntax of raise keyword

Syntax of raise keyword

For example, take only even numbers as input from the user but the user enters an odd number, in this case, we will raise a custom exception and stop the normal flow of the program (to handle this situation).

num = int(input("Enter Even number: "))
if num % 2 == 0:
    print(f"{num} is even")
else:
    raise ValueError("Enter number is not even, please enter even number")

Output-1:

Enter Even number: 5
Traceback (most recent call last):
  File "c:\Users\saurabh\Desktop\react-1\raise.py", line 5, in <module>
    raise ValueError("Enter number is not even, please enter even number")
ValueError: Enter number is not even, please enter even number

Output-2:

Enter Even number: 10
10 is even

Types of Exception or Error

There are various types of pre-define exceptions (errors) in python few are listed below:

  1. SyntaxError
  2. TypeError
  3. NameError
  4. ValueError
  5. IndexError
  6. KeyError
  7. ZeroDivisionError
  8. FileNotFoundError

You can raise any of the above exceptions (errors) according to your need (and program requirements)

For example, take string input from the user but there is one condition string length is less than or equal to 10, if the user entered string has more than 10 characters then raise an exception.

name = input("Enter your name: ")

if len(name)> 10:
    raise NameError("only 10 characters are allowed")
print(f"hello {name}")

Output-1:

Enter your name: yagyavendra
Traceback (most recent call last):
  File "c:\Users\saurabh\Desktop\react-1\raise.py", line 11, in <module>
    raise NameError("only 10 characters are allowed")
NameError: only 10 characters are allowed

Output-2:

Enter your name: joy
hello joy

raise Exception with Custom Name

You can also raise exceptions with custom names (we can create a custom exception to increase the readability of the code).

To create an exception with a custom name, simply create a class with a custom name and inherited a valid pre-define exception (also called a base exception class), after that just use the pass keyword to indicate that you don’t want to add any additional functionality to the class (i.e., you’re only using it to define a custom exception type).

Syntax of raise a custom exception

let’s see with the help of an example.

# password validate

# create error with custom name
class PasswordToShortErr(ValueError):
    pass

def Validate(password):
    if len(password) < 8:
        # Use custom exception
        raise PasswordToShortErr("Password must contain 8 or more then 8 characters")
    return "password validate"

username = input("Enter your name: ")
pas = input('Enter a password: ')

Validate(pas) # call a function

print(f"Hello {username}, your password is validate")

Output-1:

Enter your name: joy
Enter a password: 345
Traceback (most recent call last):
  File "c:\Users\saurabh\Desktop\react-1\raise.py", line 17, in <module>
    Validate(pas) # call a function
  File "c:\Users\saurabh\Desktop\react-1\raise.py", line 11, in Validate
    raise PasswordToShortErr("Password must contain 8 or more then 8 characters")
__main__.PasswordToShortErr: Password must contain 8 or more then 8 characters

Output-2:

Enter your name: allinpython
Enter a password: 12345678
Hello allinpython, your password is validate

Related Topic:

Explain try-except in Python with an example

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment