Javatpoint Logo
Javatpoint Logo

Python Raise an Exception

The raise statement in Python is used to raise an exception. Try-except blocks can be used to manage exceptions, which are errors that happen while a programme is running. When an exception is triggered, the programme goes to the closest exception handler, interrupting the regular flow of execution.

  • The raise keyword is typically used inside a function or method, and is used to indicate an error condition.
  • We can throw an exception and immediately halt the running of your programme by using the raise keyword.
  • Python looks for the closest exception handler, which is often defined using a try-except block, when an exception is triggered.
  • If an exception handler is discovered, its code is performed, and the try-except block's starting point is reached again.
  • If an exception handler cannot be located, the software crashes and an error message appears.

An illustration of how to raise an exception is provided below:

Example-1:

Code

Output:

An error occurred: Cannot divide by zero. 

In this illustration, the division function accepts the inputs a and b, and if b equals zero, an exception is raised. The try block catches this exception, and the unless block prints the error message.

Example-2:

Code

Output:

An error occurred: Age must be 18 or above.

The check age method in this illustration accepts the input age and throws an exception if age is less than 18. The try block catches this exception, and the unless block prints the error message. This demonstrates how you can raise and handle exceptions in Python.

You can raise any type of exception, such as ValueError, TypeError, KeyError, etc. to indicate specific errors in your code.

Code

Output:

Invalid Value

We attempt to change the string "a" to an integer in this instance, which results in a ValueError. The first unless block recognises the exception and produces a message stating that the value is incorrect. A different kind of exception would be handled by the next except block if it were to arise.

The finally block can also be employed to run code that has to be run whether or not this exception was triggered. For instance:

Code

Output:

Cannot divide by zero.
The finally block is always executed.






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA