PythonSyntax and keywords
try, except, else, finally
Exception handling: catching errors without stopping the program.
Example
#Python
def to_points(text):
try:
value = int(text)
except ValueError:
print(f"'{text}' is not a number")
return 0
else:
return value
finally:
print("Checked:", text)
print(to_points("42"))
print(to_points("forty"))Resultsaved result, you can check it
Checked: 42
42
'forty' is not a number
Checked: forty
0
Definition and usage
#A try block contains code that might raise an exception. If an error occurs, Python jumps to the matching except block instead of stopping the program. You can handle different exception types in separate blocks.
The optional else block runs only when there was no error in try, and finally always runs, regardless of the outcome. finally is used for cleanup, for example closing a connection.
Catch specific exceptions, such as ValueError or KeyError. A bare except: catches everything, including the user interrupting the program, and hides real bugs.
Syntax
#Syntax
try:
...
except ExceptionType as error:
...
else:
...
finally:
...More examples
#Python
scores = {"emma": 92}
for key in ["emma", "jack"]:
try:
print(100 / scores[key])
except KeyError as error:
print("No such student:", error)
except ZeroDivisionError:
print("Division by zero")Resultsaved result, you can check it
1.0869565217391304
No such student: 'jack'
Good practices
#- Only catch exceptions you can handle sensibly. Let the rest propagate.
- Keep the
tryblock short: only the lines that can actually raise the error you are handling.
Related entries
#Spotted a mistake or missing an example? Write to us.