A Python program ends as soon as it meets an error. In this Python tutorial, let us see Exceptions and handling with suitable examples.
Introduction of Python Exceptions
When an error occurs, or exception, Python terminates the process and generate an error message.
Those exceptions may be handled using the following statements,
- The try block lets you test a block of code for errors
- The except block lets you handle the error
try: print(x) except: print("An exception occurred")
note: The try block will generate an exception because x is not defined.
The “finally” block, if specified, will be executed despite if the try block raises an error or not.
try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished")
This can be useful to close objects and clean up resources.
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.
x = -1 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.