Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

What is the raise keyword in Python?

Sumit Sharma

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The raise keyword in Python is mainly used for exception handling. Exception handling handles exceptions or errors so that the system does not malfunction due to incorrect code.

The main tools in exception handling are:

  • try and except
  • finally
  • raise

Solution

The raise keyword raises a specific exception when a condition is met or the code encounters an error.

The exception raised by the program may either be an exception instance or an exception class. When you use the raise keyword, you can define what kind of error the machine should raise for a particular exception.

Code

The code below demonstrates a program that raises an error if the value of the variable x is lower than 00:

# Input
x = -1

# Use of "raise"
if x < 0:
  raise Exception("Sorry, no numbers below zero")

Explanation

The code above takes the following actions:

  • In line 2, the value of x is initialized as 1-1.

  • In line 5, the condition checks whether the value of x is less than 00. Since x is a negative number, the condition is satisfied.

  • In line 6, an exception is raised with the raise keyword. The code produces an error that corresponds to the message associated with the exception.

The raise keyword can be helpful for developers, as statements that are easy to decipher can be printed to signify errors.

RELATED TAGS

communitycreator
python

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring