Python Raise an ExceptionThe 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: 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. Next TopicRandom Password Generator in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India