
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
Explain Try, Except, and Else Statement in Python
In Python, the try, except, and else statements are used to handle exceptions and define specific blocks of code that should execute based on whether an error occurs or not. This helps you manage errors and separate successful code from error-handling logic.
Using "try" and "except"
The try block contains code that might raise an exception. If an exception occurs, the control jumps to the except block, which contains code to handle that exception.
Example: Handling division by zero
In the following example, we are dividing a number by zero, which raises an exception that is handled by the except block -
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero.")
We get the following output -
Cannot divide by zero.
Using "else" with "try" and "except"
The else block is executed only if no exception occurs in the try block. It helps to keep successful code separate from the error-handling code.
Example: No exception Occurs
In the following example, we are successfully converting a string to an integer, so the else block runs -
try: value = int("100") except ValueError: print("Invalid input.") else: print("Conversion successful:", value)
We get the following output -
Conversion successful: 100
Using else to separate clean logic
The statements in the else block are executed only if the contents of the try block run without any error.
Example: Performing Operation after a Successful try
In the following example, we are performing an addition after converting input successfully. The else block ensures it runs only if the conversion is error-free -
try: num1 = int("50") num2 = int("20") except ValueError: print("Conversion failed.") else: total = num1 + num2 print("Total is:", total)
We get the following output -
Total is: 70
Exception occurs, else skipped
If an exception is raised inside the try block, the else block is skipped and only the except block is executed.
Example: Failing string to int conversion
In the following example, the conversion fails due to an invalid string, so the except block handles it and the else block is skipped -
try: number = int("abc") except ValueError: print("Conversion failed.") else: print("You will not see this line.")
We get the following output -
Conversion failed.