Try except Statement in Python
The try except statement in Python allows you to catch one or more errors during the execution of a block of code through exception handling.
try:
block of code
except error1:
instruction1
The try block executes the indented instructions.
- If there are no errors, it executes the block and moves to the next instruction after the try block.
- If an error occurs, the try statement checks if the error code matches any listed after an except clause.
- If it matches, it executes the corresponding indented instruction. Then, it proceeds to the next instruction after the try except structure without stopping the program.
- If it doesn't match, the Python interpreter raises an error and stops the program.
What is try except for? It prevents the program from crashing. If something unexpected happens, the try except structure allows the programmer to catch and fix it automatically, without halting the program.
A Practical Example
This script divides two values.
However, the divisor (b) is zero.
- a=10
- b=0
- try:
- print(a/b)
- except ZeroDivisionError:
- print("Warning, division by zero")
Under normal circumstances, this would raise an error.
print(a/b)
ZeroDivisionError: division by zero
In this case, the try statement checks if the error code is listed in the except clause on line 5.
It finds it and executes line 6.
Warning, division by zero
The script continues running without stopping.
Handling Multiple Exceptions
You can include multiple except clauses in a try except structure.
This way, you can handle different exceptions separately.
try:
block of code
except error1:
instruction1
except error2:
instruction2
The try statement checks the clauses sequentially, from the first to the last.
If it finds a matching error code, it executes the corresponding indented block of instructions.
A Practical Example
Here’s an example of handling two exceptions.
- try:
- print(a/b)
- except ZeroDivisionError:
- print("Warning, division by zero")
- except IndexError:
- print("Warning, index error")
Catching All Errors
To catch all exceptions, simply omit the error code after an except clause.
This type of exception is called a default except and should be placed after all other except clauses.
try:
block of code
except error1:
instruction1
except error2:
instruction2
except:
instruction3
If an error occurs, the interpreter checks if the code matches error1 or error2.
If it doesn’t match, it executes the indented block within the default except clause, i.e., instruction 3.
A Practical Example
This code handles two exceptions.
- try:
- print(a/b)
- except ZeroDivisionError:
- print("Warning, division by zero")
- except IndexError:
- print("Warning, index error")
- except:
- print("An unknown error occurred")
If neither exception matches the error, the Python interpreter displays the message “An unknown error occurred”.
Catching an Error Without Doing Anything
To catch an error without taking any action, you can use the pass statement.
try:
block of code
except error1:
pass
After the except clause, you must include some code in the indented block.
Otherwise, the interpreter will raise an error.
The pass statement acts as a placeholder. It does nothing at all.
The finally Clause
The finally clause is an optional part of the try except structure.
It is executed at the end, regardless of whether an exception was raised or not.
try:
...
except:
...
finally:
...
The instructions inside the finally block are always executed, even if no exceptions occur.
A Practical Example
In this script, I use the finally clause within the try except structure.
- try:
- print("1")
- except:
- print("2")
- finally:
- print("3")
The script's output is:
1
3
The else Clause
The else clause is another optional part of the try except structure.
It is executed only if no exceptions are raised.
try:
...
except:
...
else:
...
If an exception is raised, the else clause is not executed by the Python interpreter.
A Practical Example
In this script, I use the else clause.
- try:
- if x > 0: print("positive number")
- except:
- print("error: the number is a string")
- else:
- print("calculation completed successfully")
If x is a number (e.g., x = 5), the script runs correctly, and no exception occurs.
Therefore, the script’s output is:
positive number
calculation completed successfully
If x is a string (e.g., x = "5"), the script raises an exception.
The script’s output is:
error: the number is a string
And so on.