- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
The try-finally Clause in Python
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 −
try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
You cannot use else clause as well along with a finally clause.
#!/usr/bin/python try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will produce the following result −
Error: can't find file or read data
Same example can be written more cleanly as follows −
#!/usr/bin/python try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print "Going to close the file" fh.close() except IOError: print "Error: can\'t find file or read data"
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.
- How to use the try-finally clause to handle exception in Python?
- Explain try, except and finally statements in Python.
- Try-Catch-Finally in C#
- Try/catch/finally/throw keywords in C#
- Explain Try/Catch/Finally block in PowerShell
- Flow control in try catch finally in C#
- What are try, catch, finally blocks in Java?
- Flow control in try catch finally in Java programming.
- Flow control in a try catch finally in Java
- Can we write any statements between try, catch and finally blocks in Java?
- Why variables defined in try cannot be used in catch or finally in java?
- Finally keyword in Python
- try and except in Python
- try and except in Python Program