Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Exception_Handling_Python

Exception handling in Python allows developers to manage errors during program execution using try, except, else, and finally blocks. It helps prevent crashes, improves user experience with meaningful error messages, and ensures proper cleanup actions. The document provides examples of handling specific exceptions like ZeroDivisionError and ValueError, as well as the use of the finally block.

Uploaded by

Chandu Alagani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Exception_Handling_Python

Exception handling in Python allows developers to manage errors during program execution using try, except, else, and finally blocks. It helps prevent crashes, improves user experience with meaningful error messages, and ensures proper cleanup actions. The document provides examples of handling specific exceptions like ZeroDivisionError and ValueError, as well as the use of the finally block.

Uploaded by

Chandu Alagani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Exception Handling in Python

Exception handling in Python is a way to handle errors or exceptions that occur during program
execution, preventing the program from crashing. It allows developers to handle unexpected
situations gracefully using try, except, else, and finally blocks.

Basic Syntax of Exception Handling:

try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a number.")
except Exception as e:
print("An unexpected error occurred:", e)
else:
print("No errors occurred.")
finally:
print("Execution completed.")

Handling ZeroDivisionError
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")

Handling ValueError
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter an integer.")

Handling Multiple Exceptions


try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)
Using finally Block
try:
file = open("sample.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing the file (if opened).")

Why Use Exception Handling?


1. Prevents program crashes due to runtime errors.
2. Improves user experience by providing meaningful error messages.
3. Ensures important cleanup actions (e.g., closing files, releasing resources).
4. Makes debugging easier by identifying specific errors.

You might also like