The “try/except” statement
In python to handle exceptions (errors) we use the try statement. When an error occurs, or exception, python will stop and attempt to generate an error message. These errors are handled by the try/except statement.
The “try/except” statement syntax
If the indented code inside the try statement errors the except statement will handle it. Here we are looking for a ValueError exception. The except statement will get called as the code inside the try statement will error.
The try block lets you test a block of code for errors.
The except statement lets you handle the error.
The finally statement lets you execute code, without taking the result of the try and except
This is a similar example to the first one. ValueError gets raised and finished gets printed. Anything inside finally will get ran after the try/except statement finishes. If we want to print the error message we can do except Exception as e:, this will print an important portion of the exception.
To raise errors we use the raise keyword. For example, raise ValueError. Here is the list of all python exceptions, these do not include library/modules exceptions which you’ll learn later on! https://docs.python.org/3/library/exceptions.html
Some of the exceptions you’ll commonly come by include but not limited to,
- Unresolved Reference Error