The try except statement can handle exceptions. Exceptions may happen when you run a program.
Exceptions are errors that happen during execution of the program. Python won’t tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.
An abrupt exit is bad for both the end user and developer.
Instead of an emergency halt, you can use a try except statement to properly deal with the problem. An emergency halt will happen if you do not properly handle exceptions.
Related course: Complete Python Bootcamp: Go from zero to hero in Python
Lets take this scenario: _The program asks for numeric user input. Instead the user types characters in the input box. The program normally would crash. _
The try except statement prevents the program from crashing and properly deals with it.
Entering invalid input, makes the program continue normally:
The try except statement can be extended with the finally keyword, this will be executed if no exception is thrown:
The program continues execution if no exception has been thrown.
There are different kinds of exceptions: ZeroDivisionError, NameError, TypeError and so on. Sometimes modules define their own exceptions.
- Can try-except be used to catch invalid keyboard input?
- Can try-except catch the error if a file can’t be opened?
- When would you not use try-except?