python / beginner
Snippet
Basic Exception Handling
Exception handling prevents your program from crashing when errors occur. The try block contains code that might fail, while the except block handles the error.
snippet.py
1
2
3
4
try:number = int("abc")except ValueError:print("That is not a valid number!")
Breakdown
1
try:
Starts a block where you expect potential errors.
2
number = int("abc")
Attempts to convert a non-numeric string to an integer, which fails.
3
except ValueError:
Catches the specific error that happens during conversion.