×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python raise Keyword

By IncludeHelp Last updated : December 07, 2024

Description and Usage

The except is a keyword (case-sensitive) in python, it is used to raise an Exception/Error with a customized message and stops the execution of the programs.

It is very useful when you want to work with the input validations. For example – if you are working with the positive numbers and someone inputs a negative number, in this case, we can raise an error and stop the program’s execution.

Syntax

Syntax of raise keyword:

if test_condition:
  raise Exception(Message)

Sample Input/Output

Input:
string = "Hello"

if string=="Hello" or string=="Hi" or string=="Bye":
  raise Exception("This word is not allowed")

Output:
Exception: This word is not allowed

Example 1

Input a positive number and raise an exception if input is a negative value .

# python code to demonstrate example of 
# raise keyword 

# Input a positive number and raise an exception 
# if input is a negative value 

num = int(input("Enter a positive number: "))

if num<0:
    raise Exception("Please input only positive value ")

print("num = ", num)

Output

First run:
Enter a positive number: 20
num =  20

Second run:
Enter a positive number: -10
Traceback (most recent call last):
  File "/home/main.py", line 10, in <module>
    raise Exception("Please input only positive value ")
Exception: Please input only positive value

Example 2

Input a string and raise an exception on specific words.

# python code to demonstrate example of 
# raise keyword 

# Input a string and raise an exception on specific words

string = input("Input a string: ")

# words - we are checking
# 'Hello', 'Hi' or 'Bye'
if string=="Hello" or string=="Hi" or string=="Bye":
    raise Exception("This word is not allowed")

print("The input was: ", string)

Output

First run:
Input a string: IncludeHelp
The input was:  IncludeHelp

Second run:
Input a string: Hello 
Traceback (most recent call last):
  File "/home/main.py", line 11, in <module>
    raise Exception("This word is not allowed")
Exception: This word is not allowed

Third run:
Input a string: Bye
Traceback (most recent call last):
  File "/home/main.py", line 11, in <module>
    raise Exception("This word is not allowed")
Exception: This word is not allowed
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement



Copyright © 2024 www.includehelp.com. All rights reserved.