python / beginner
Snippet
Basic Exception Handling
Using try and except blocks prevents your program from crashing when an error occurs by allowing you to handle the exception gracefully.
snippet.py
1
2
3
4
try:number = int("not_a_number")except ValueError:print("Caught an error: That was not a valid number!")
Breakdown
1
try:
Begins a block where you expect a potential error might happen.
2
except ValueError:
Executes this code block only if a ValueError occurs inside the try block.