-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_exceptions_tutorial.py
More file actions
52 lines (45 loc) · 1.6 KB
/
20_exceptions_tutorial.py
File metadata and controls
52 lines (45 loc) · 1.6 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
def divide_numbers(a, b):
try:
# Trying to execute the operation
result = a / b
except ZeroDivisionError:
# Handling a specific error: division by zero
return "Error: Cannot divide by zero!"
except TypeError:
# Handling another error: incorrect data type
return "Error: Only numbers should be entered!"
except Exception as e:
# Catching any other unexpected errors
return f"An unexpected error occurred: {e}"
else:
# Executes if no exceptions occurred in the try block
return f"Result: {result}"
finally:
# Executes ALWAYS (useful for closing files or connections)
print("Completing division operation.")
# Usage examples
print(divide_numbers(10, 2)) # Success
print(divide_numbers(10, 0)) # ZeroDivisionError
print(divide_numbers(10, "2")) # TypeError
print("-" * 20)
# How to handle multiple errors in one block
def multi_catch_example(value):
try:
# Let's say we're trying to convert to int and divide
res = 100 / int(value)
print(f"Result: {res}")
except (ValueError, ZeroDivisionError) as e:
# Catching either a value error or division by zero
print(f"Input data '{value}' caused an error: {e}")
multi_catch_example("abc") # ValueError
multi_catch_example("0") # ZeroDivisionError
print("-" * 20)
# Example with raising a custom error
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return f"Age accepted: {age}"
try:
print(check_age(-5))
except ValueError as e:
print(f"Caught exception: {e}")