- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use the try-finally clause to handle exception in Python?
So far the try statement had always been paired with except clauses. But there is another way to use it as well. The try statement can be followed by a finally clause. Finally clauses are called clean-up or termination clauses, because they must be executed under all circumstances, i.e. a "finally" clause is always executed regardless if an exception occurred in a try block or not.
One very important point is that we can either define an “except” or a “finally” clause with every try block. You can’t club these together. Also, you shouldn’t use the “else” clause along with a “finally” clause.
Given code can be rewritten as follows
try: foo = open ( 'test.txt', 'w' ) foo.write ( "It's a test file to verify try-finally in exception handling!!") print 'try block executed' finally: foo.close () print 'finally block executed'
try block executed finally block executed
- The try-finally Clause in Python
- How to handle an exception in Python?
- How to handle Python exception in Threads?
- How to use Grouping clause to handle NULLS in Oracle?
- How do you handle an exception thrown by an except clause in Python?
- Try-Catch-Finally in C#
- How to handle python exception inside if statement?
- Explain try, except and finally statements in Python.
- How to handle the Runtime Exception in Java?
- How to handle exception inside a Python for loop?
- How to handle a python exception within a loop?
- How to handle an exception in JSP?
- How to handle the exception using UncaughtExceptionHandler in Java?
- Try/catch/finally/throw keywords in C#