In this post, we are going to learn about Python Try and Except block. This is a very common function when we come to commercial applications. Because this function is basically used to debug your program codes inside an especially block and return an Exception or next step when your main program raises an error. This very uses full to keep your program alive without getting break or crash when getting an error.
Try and Except Blocks
Try and accept is mainly working on three basic blocks. They are try, except and finally.
- Try - This is used to check your code whether it is working or not.
- Except - This is used to get the error exception or run the next step when your code went wrong inside the try block.
- Finally - This is the last block we are using in this block pattern. And this is used to return the final command/task/program whether your code is working or not. This is not caused if a try is true or false and it just returns a final command
Note: You need to keep in mind that you can't just use try, you might need to use except with the try block. However, there is no recommendation to use finally with the try and except.
How to use Try and Except...
How to get an Exception for a Specific error...
StandardError - This error is raised by a stop iteration. It means mostly an error of loops like FOR.
OverflowError - This error is raised by reaching a maximum value of a calculation. This is very helpful when making a simple Python Calculator.
ImportError - This error is rasing when there is a module importing error or module not found error.
NameError - This error is raised when there is a variable error or value not found error.
RuntimeError - This error is raised when the error does not belong to any category.