
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Use Except Clause with No Exceptions in Python
In Python, the except clause is used to handle exceptions that may occur inside a try block. But what happens if no exceptions are raised? The except block is simply skipped.
When No Exceptions Occur
If the code inside the try block executes without raising any exceptions, the except block is ignored, and the program continues normally.
Example: No exceptions raised
In this example, we are performing a simple division that doesn't raise an exception, so the except block does not run -
try: result = 10 / 2 print("Division successful:", result) except ZeroDivisionError: print("This won't be printed.")
We get the following output -
Division successful: 5.0
Using else for Successful Execution
You can use an else block along with try and except to specify code that should run only if no exception occurs. This helps to separate normal execution from error-handling code.
Example
In this example, we are using the else block to execute code only when the try block runs successfully -
try: value = int("123") except ValueError: print("Invalid input.") else: print("Conversion succeeded:", value)
We get the following output -
Conversion succeeded: 123
Using finally Even Without Exceptions
The finally block runs irrespective of whether an exception occurs or not. It is usually used for cleanup actions such as closing files or releasing resources.
Example
In this example, even though no exception occurs, the finally block executes -
try: print("Everything is fine.") except: print("An error occurred.") finally: print("This will always execute.")
We get the following output -
Everything is fine. This will always execute.
Empty except Clause with No Exception
If you write an except block with no specific error and no error is raised, it will simply be skipped.
However, using a bare except (without specifying an error type) is not recommended unless it is really needed. It can catch unexpected errors and make debugging harder, so it is better to catch specific exceptions whenever possible.
Example: Bare except not triggered
In this example, the except clause is not executed because there is no error -
try: print("Code is running.") except: print("Caught an error.")
We get the following output -
Code is running.