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.
An illustration of how to raise an exception is provided below:
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.
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.
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:
Cannot divide by zero. The finally block is always executed.
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week