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.

Usual Flow of Execution When an Error is Encountered

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:

  1. 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/except statement.
  2. If a run-time error does occur during the execution of the block of code in the try statement, it will execute the except statement.
Summary: How does the try/except statement work?

  • First, the try clause is executed.
  • If no exception occurs, the except clause is skipped and execution of the try statement is finished.
  • If an exception occurs during execution of the try keyword, the except clause is executed, and then execution continues after the try/except block.
  • If an exception occurs which does not match the exception defined in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

Why use try/except?

Specifying the Exception Type

What is an 'exception'?

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 
    # ...

  1. 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. ↩︎

Powered by Forestry.md