-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21.Custom_Error.py
More file actions
69 lines (36 loc) · 1.26 KB
/
21.Custom_Error.py
File metadata and controls
69 lines (36 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# ================================
# Raising Custom Errors in Python
# ================================
# In Python, sometimes you want to give your own error message instead of Python’s default message.
# For that, you define a custom exception class and then raise it.
# Why Use Custom Errors?
# ✔ Better understanding of what went wrong
# ✔ Makes big programs easier to debug
# ✔ Helps to enforce rules (e.g., age, number ranges)
# Keyword Use:
# raise Throw an error
# Exception Base class for all errors
# try Code that may cause error
# except Handle the error
age = int(input("Enter your age: "))
if age < 18:
raise AgeError("You must be 18 or above!")
else:
print("Access granted")
# Handling (Catching) Custom Errors with try-except
try:
age = int(input("Enter age: "))
if age < 18:
raise AgeError("Not eligible to vote!")
except AgeError as e:
print("Custom Error:", e)
# Example with Two Custom Errors
class NegativeNumberError(Exception):
pass
number = int(input("Enter a number: "))
if number < 0:
raise NegativeNumberError("Negative numbers are not allowed")
elif number == 0:
raise ValueError("Zero is not allowed (built-in error)")
else:
print("Valid number:", number)