Categories: python

Python Exception Handling – III(Raise Keyword )

In Python, the raise keyword is primarily used for exception handling. Exception handling is responsible for handling exceptions or errors so that the system does not fail due to incorrect code.

The raise keyword generates an error and halts the program’s control flow. It is used to invoke the current exception handler so that it can be handled further up the call stack.

Syntax:

raise {name_of_ the_ exception_class}

Example:

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

# Input
x = -1

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

Output:

Traceback (most recent call last):
  File "<string>", line 6, in <module>
Exception: Sorry, no numbers below zero allowed

Note: While raising an error, we can also specify the type of error and, if necessary, print out a text.

Raising an exception Without Specifying Exception Class:

There is no requirement to provide an exception class when we use the raise keyword. When we use the raise keyword without specifying an exception class name, it reraises the last exception that occurred. This is used generally inside an except code block to reraise an exception that is caught.

Example:

a = 10
b = 'a'
try:
    print(a/b)
except ValueError:
    raise

Output:

Traceback (most recent call last):
  File "<string>", line 4, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Benefits of the raise keyword:
  • It allows us to raise exceptions when we encounter situations where execution cannot continue.
  • It allows us to reraise an exception that has been caught.
  • Raise gives us the ability to throw one exception at any time.
  • It is useful when working with input validations.

Note: also read about Python Exception Handling – II(Finally Keyword )

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago