About Try-Except
What is the Try/Except Statement?
The try/except control structure provides a way to process a run-time error and continue on with program execution.
When a run-time error is encountered, the python interpreter does not try to execute the rest of the code. You have to make some change in your code and rerun the whole program.
How does the Try/Except work?
The basic syntax of a try/except statement consists of:
try:
# Code that might raise an exception
# ...
except:
# Code to handle the exception
# ...
Two Possible Outcomes:
- If the block of code executes without any runtime errors[1], the program will carry on with the rest of the code after the
try/exceptstatement. - If a run-time error does occur during the execution of the block of code in the
trystatement, it will execute theexceptstatement.
try/except statement work?
- First, the
tryclause is executed. - If no exception occurs, the except clause is skipped and execution of the
trystatement is finished. - If an exception occurs during execution of the
trykeyword, theexceptclause is executed, and then execution continues after the try/except block. - If an exception occurs which does not match the exception defined in the
exceptclause, it is passed on to outertrystatements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
Why use try/except?
- When you have a block of code to execute that may run incorrectly depending on conditions you cannot foresee at the time you are writing the code.
- Essentially used to compensate for potential errors.
Specifying the Exception Type
Exceptions are errors detected during execution that cannot be handled using the normal flow-of-control. With the except keyword, we can specify what the program should do should it encounter a specified error.
If you want to execute a block of code for a specified kind of error, we can specify the ExceptionType after the except keyword. This allows you to only handle a restricted class of error.
try:
# Code that might raise an exception
# ...
except ExceptionType:
# Code to handle the exception
# ...
Example: Print message if the try block raises a NameError
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Catching All Run-Time Errors
If you write except Exception: all runtime errors will be handled.
try:
# Code that might raise an exception
# ...
except Exception:
# Code to handle the exception
# ...
A run-time error is an error that occurs while a program is running. This can lead to the program being terminated or behaving unexpectedly. Unlike syntax errors that are detected by the Python interpreter before the program starts executing, run-time errors occur as the program is running. ↩︎