Get The Most Affordable Hosting in the World!
Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.
Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!
Get Started Now!You can use a finally: block along with a try: block. The finally: block is a place to put any code that must execute, whether the try-block raised an exception or not.
The syntax of the try-finally statement is this −
Note − You can provide except clause(s), or a finally clause, but not both. You cannot use else clause as well along with a finally clause.
Example
If you do not have permission to open the file in writing mode, then it will produce the following output −
Error: can't find file or read data
The same example can be written more cleanly as follows −
When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.
Exception with Arguments
An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows −
If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.
Example
Following is an example for a single exception −
It will produce the following output −
The argument does not contain numbers invalid literal for int() with base 10: 'xyz'
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.