error handling
This commit is contained in:
97
src/basic/error_handling.py
Normal file
97
src/basic/error_handling.py
Normal file
@@ -0,0 +1,97 @@
|
||||
# Error Handling
|
||||
|
||||
# Basic try / except
|
||||
|
||||
try:
|
||||
number = int('anikuttan') # invalid conversion
|
||||
except:
|
||||
print("Something went worng")
|
||||
|
||||
|
||||
try:
|
||||
x = int("abc") # invalid conversion
|
||||
except ValueError:
|
||||
print("Oops! That was not a number.")
|
||||
|
||||
|
||||
# Handling Multiple Exceptions
|
||||
try:
|
||||
result = 10 / 0
|
||||
except ZeroDivisionError:
|
||||
print("You cannot divide by zero!")
|
||||
except ValueError:
|
||||
print("Invalid value!")
|
||||
|
||||
# Catching All Exceptions
|
||||
try:
|
||||
print(10/0)
|
||||
except Exception as e:
|
||||
print(f"error {e}")
|
||||
|
||||
|
||||
# else with try
|
||||
# The else block runs only if no exception occurs.
|
||||
try:
|
||||
x = int("10")
|
||||
# x = int("abs")
|
||||
except ValueError:
|
||||
print("Invalid number")
|
||||
else:
|
||||
print("Conversion successful:", x)
|
||||
|
||||
|
||||
# finally Block
|
||||
# The finally block always runs
|
||||
try:
|
||||
x = int("as")
|
||||
except ValueError:
|
||||
print("invalid conversion")
|
||||
finally:
|
||||
print("Finally called")
|
||||
|
||||
|
||||
# Raising Exceptions
|
||||
|
||||
def withdraw(balance, amount):
|
||||
if amount > balance:
|
||||
raise ValueError("Insufficient funds!")
|
||||
else:
|
||||
return balance - amount
|
||||
|
||||
|
||||
try:
|
||||
withdraw(100, 200)
|
||||
except ValueError as e:
|
||||
print("Error:", e)
|
||||
|
||||
|
||||
# Custom Exceptions
|
||||
|
||||
class NegativeNumberError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def square_root(x):
|
||||
if x < 0:
|
||||
raise NegativeNumberError(
|
||||
"Cannot take square root of negative number!")
|
||||
return x ** 0.5
|
||||
|
||||
|
||||
try:
|
||||
print(square_root(-9))
|
||||
except NegativeNumberError as e:
|
||||
print("Custom Error:", e)
|
||||
|
||||
|
||||
# Summary
|
||||
|
||||
# try / except → catch errors
|
||||
|
||||
# else → run if no error
|
||||
|
||||
# finally → always runs
|
||||
|
||||
# raise → trigger your own error
|
||||
|
||||
# Custom exceptions → more control in big apps
|
||||
Reference in New Issue
Block a user