Tutorial
Try & Except
Sometimes, your Python code can cause errors while running. These are called exceptions. To handle them and avoid crashes, Python provides try and except blocks.
Using Try & Except
The try block contains the code that might cause an error. The except block contains code that runs if an error occurs.
- If the user enters 0, the
ZeroDivisionErroris caught. - If the user enters something that's not a number,
ValueErroris caught. - The program will not crash, and you see a friendly message instead.
Handling Multiple Exceptions in One Line
You can handle multiple exceptions using a tuple in a single except:
Using Else
The else block runs only if there is no exception:
Using Finally
The finally block always runs, even if an exception occurs:
Common Exceptions
ZeroDivisionError– dividing by zeroValueError– wrong type of inputFileNotFoundError– trying to open a missing fileTypeError– performing an invalid operation on a type
What You Learned
- Exceptions are errors that occur during program execution.
trylets you test code that might fail.excepthandles specific errors safely.elseruns if no exception occurs.finallyalways runs, useful for cleanup.- Handling exceptions prevents your program from crashing and allows graceful messages.