Spex3
    

Try-Except Blocks & Handling Specific Exceptions in Python ๐Ÿš€๐Ÿ


    

    

Pythonโ€™s try-except blocks allow you to handle errors gracefully without crashing the program.

1๏ธโƒฃ Basic try-except Block
๐Ÿ”น Without error handling, an error stops the program:


print(10 / 0) # ZeroDivisionError: division by zero
โœ… Solution: Use try-except to handle the error


try:
print(10 / 0)
except:
print("An error occurred!")
๐Ÿ”น Output:


An error occurred!
โœ” The program continues running instead of crashing.

2๏ธโƒฃ Handling Specific Exceptions
๐Ÿ”น Instead of catching all errors, handle specific ones:


try:
x = int("abc") # This causes a ValueError
except ValueError:
print("Error: Invalid number!")
๐Ÿ”น Output:


Error: Invalid number!
โœ” This ensures that only expected errors are handled.

3๏ธโƒฃ Catching Multiple Exception Types
๐Ÿ”น Use multiple except blocks to handle different errors separately:


try:
num = int(input("Enter a number: ")) # Might cause ValueError
result = 10 / num # Might cause ZeroDivisionError
except ValueError:
print("Error: Please enter a valid number!")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
๐Ÿ”น Example Runs:


Enter a number: abc
Error: Please enter a valid number!
vbnet
Copy
Edit
Enter a number: 0
Error: Cannot divide by zero!
โœ” Each error type has its own response.

4๏ธโƒฃ Catching Multiple Errors in One except Block

๐Ÿ”น If multiple errors need the same handling, use a tuple:


try:
num = int("abc") # ValueError
result = 10 / 0 # ZeroDivisionError
except (ValueError, ZeroDivisionError):
print("Error: Invalid input or division by zero!")

๐Ÿ”น Output:


Error: Invalid input or division by zero!
โœ” Shorter and cleaner than using multiple except blocks.

5๏ธโƒฃ Catching All Exceptions (Exception)

๐Ÿ”น Use Exception to catch any error (not recommended for all cases):


try:
x = int("xyz") # Causes ValueError
except Exception as e:
print(f"An error occurred: {e}")
๐Ÿ”น Output:


An error occurred: invalid literal for int() with base 10: 'xyz'
โœ” Exception is the base class for all errors, so it catches everything.

6๏ธโƒฃ Using else and finally

Block Purpose

try Code that may cause an error

except Handles the error

else Runs only if no exception occurs

finally Runs always, even if an error occurs

โœ… Example:

try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid number!")
else:
print(f"Success! The result is {result}")
finally:
print("Execution complete.")

โœ” else runs only if try succeeds.

โœ” finally always runs, useful for cleanup (e.g., closing files).

7๏ธโƒฃ Raising Exceptions (raise)

๐Ÿ”น You can manually trigger an exception using raise:


def check_age(age):
if age < 18:
raise ValueError("You must be 18 or older!")
print("Access granted.")

try:
check_age(16)
except ValueError as e:
print(f"Error: {e}")
๐Ÿ”น Output:


Error: You must be 18 or older!

8๏ธโƒฃ Summary

Concept Description

Basic try-except Handles errors to prevent crashes

Specific Exceptions except ValueError:, except ZeroDivisionError:

Multiple except Blocks Handle different errors separately

Multiple Errors in One except except (TypeError, ValueError):

Catching All Errors except Exception as e: (Use cautiously)

else Block Runs if no error occurs

finally Block Runs always (cleanup code)

Raising Exceptions raise ValueError("Custom error")


    Date: 2025-03-24 00:00:00.000000