

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Explain try, except and finally statements in Python.
In exception handling in Python, we use the try and except statements to catch and handle exceptions. The code within the try clause is executed statement by statement.
If an exception occurs, the rest of the try block is skipped and the except clause is executed.
Example
try: 'apple' + 6 except Exception: print "Cannot concatenate 'str' and 'int' objects"
Output
Cannot concatenate 'str' and 'int' objects
We avoid the traceback error message elegantly with a simple message like above by using try except statements for exception handling.
In addition to using an except block after the try block, we can also use the finally block. The finally clause is optional. It is intended to define clean-up actions that must be executed under all circumstances
A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.
Actions, like closing a file, GUI or disconnecting from the network, are performed in the finally clause to guarantee execution.
Here is an example of file operations to illustrate finally statement.
Example
try: f = open("foo.txt",encoding = 'utf-8') # perform file operations finally: f.close()
This type of statement makes sure that the file is closed whether an exception occurs or not.
- Related Questions & Answers
- Explain Try, Except and Else statement in Python.
- try and except in Python
- Explain Try/Catch/Finally block in PowerShell
- try and except in Python Program
- Explain try and catch statements in JavaScript with examples.
- Can we write any statements between try, catch and finally blocks in Java?
- The try-finally Clause in Python
- Try-Catch-Finally in C#
- Try/catch/finally/throw keywords in C#
- Flow control in try catch finally in Java
- Flow control in try catch finally in C#
- What are try, catch, finally blocks in Java?
- Flow control in a try catch finally in Java
- Flow control in try catch finally in Java programming.
- How to use the try-finally clause to handle exception in Python?