Raise exception example python

Python Raise an Exception

As a Python developer you can choose to throw an exception if a condition occurs.

To throw (or raise) an exception, use the raise keyword.

Example

Raise an error and stop the program if x is lower than 0:

if x < 0:
raise Exception(«Sorry, no numbers below zero»)

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example

Raise a TypeError if x is not an integer:

if not type(x) is int:
raise TypeError(«Only integers are allowed»)

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python Raise Exception

Summary: in this tutorial, you’ll learn how to raise exceptions by using the Python raise statement.

Introduction to the Python raise statement

To raise an exception, you use the raise statement:

raise ExceptionType()Code language: Python (python)

The ExceptionType() must be subclass of the BaseException class. Typically, it is a subclass of the Exception class. Note that the ExceptionType doesn’t need to be directly inherited from the Exception class. It can indirectly inherit from a class that is a subclass of the Exception class.

The BaseException class has the __init__ method that accepts an *args argument. It means that you can pass any number of arguments to the exception object when raising an exception.

The following example uses the raise statement to raise a ValueError exception. It passes three arguments to the ValueError __init__ method:

try: raise ValueError('The value error exception', 'x', 'y') except ValueError as ex: print(ex.args)Code language: Python (python)
('The value error exception', 'x', 'y')Code language: plaintext (plaintext)

Reraise the current exception

Sometimes, you want to log an exception and raise the same exception again. In this case, you can use the raise statement without specifying the exception object.

For example, the following defines a division() function that returns the division of two numbers:

def division(a, b): try: return a / b except ZeroDivisionError as ex: print('Logging exception:', str(ex)) raiseCode language: Python (python)

If you pass zero to the second argument of the division() function, the ZeroDivisionError exception will occur. However, instead of handling the exception, you can log the exception and raise it again.

Note that you don’t need to specify the exception object in the raise statement. In this case, Python knows that the raise statement will raise the current exception that has been caught by the except clause.

The following code causes a ZeroDivisionError exception:

division(1, 0)Code language: Python (python)

And you’ll see both the logging message and the exception in the output:

Logging exception: division by zero Traceback (most recent call last): File "c:/pythontutorial/app.py", line 9, in division(1, 0) File "C:/pythontutorial/app.py", line 3, in division return a / b ZeroDivisionError: division by zeroCode language: plaintext (plaintext)

Raise another exception during handling an exception

When handling an exception, you may want to raise another exception. For example:

def division(a, b): try: return a / b except ZeroDivisionError as ex: raise ValueError('b must not zero')Code language: Python (python)

In the division() function, we raise a ValueError exception if the ZeroDivisionError occurs.

If you run the following code, you’ll get the detail of the stack trace:

division(1, 0)Code language: Python (python)
Traceback (most recent call last): File "C:/pythontutorial/app.py", line 3, in division return a / b ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/pythontutorial/app.py", line 8, in division(1, 0) File "C:/pythontutorial/app.py", line 5, in division raise ValueError('b must not zero') ValueError: b must not zeroCode language: plaintext (plaintext)

First, the ZeroDivisionError exception occurs:

Traceback (most recent call last): File "C:/pythontutorial/app.py", line 3, in division return a / b ZeroDivisionError: division by zeroCode language: plaintext (plaintext)

Second, during handling the ZeroDivisionError exception, the ValueError exception occurs:

Traceback (most recent call last): File "C:/pythontutorial/app.py", line 8, in division(1, 0) File "C:/pythontutorial/app.py", line 5, in division raise ValueError('b must not zero') ValueError: b must not zeroCode language: plaintext (plaintext)

Summary

  • Use the Python raise statement to raise an exception.
  • When handling exception, you can raise the same or another exception.

Источник

Читайте также:  Двойные квадратные скобки javascript
Оцените статью