16. Python Try/Except
Python Try / Except
When executing Python code, unexpected things can happen: invalid user input, missing files, or network outages. When Python hits an error, it stops execution immediately and generates an error message. This is called raising an Exception.
If exceptions are not handled, your entire program crashes. Using try...except blocks allows you to catch these errors, handle them gracefully, and keep your application running safely.
The try and except Blocks
The try block lets you test a block of code for errors. The except block lets you handle the error if one occurs in the try block.
Without the try block, the program would have crashed instantly with a NameError, and the final print statement would never execute.
Catching Specific Exceptions
Using a bare except: catches absolutely everything. This is considered bad practice because it masks unexpected bugs. You should specify exactly which error you are expecting to catch.
Multiple Exceptions
You can define as many exception blocks as you want. This lets you execute a different block of code depending on what kind of error occurred.
Accessing the Exception Object
Sometimes you need to know the exact details of the error that occurred. You can capture the exception object itself using the as keyword.
The else Keyword
You can use the else keyword to define a block of code to be executed if no errors were raised in the try block.
The finally Keyword
The finally block, if specified, will be executed regardless of whether the try block raised an error or not. This is extremely useful for closing objects and cleaning up resources.
Even if the try block crashed and wasn't caught, or if it hit a return statement, the finally block is guaranteed to run.
Raising an Exception
As a Python developer, you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
The program halts immediately and prints your custom error message. This is how you enforce rules in your functions.
Raising Specific Errors
You can define what kind of error to raise. This makes it easier for other developers to catch specific problems when they use your code.
Knowledge Check
Ready to test your understanding of 16. Python Try/Except?