-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathexception_handling.py
46 lines (36 loc) · 1014 Bytes
/
exception_handling.py
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
# Exception Handling in Python
## What is exception handling?
Exception handling is the process of responding to exceptions when a computer program runs. An exception occurs when an unexpected event happens that requires special processing.
## Python exception handing:
The `try` block lets you test a block of code for errors.
The `except` block lets you handle the error.
The `finally` block lets you execute code, regardless of the result of the try- and except blocks.
## How to use:
```
try:
print(x)
except:
print("An exception occurred")
```
## Example
without exception handling
```
>>> print( 0 / 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
```
after exception handling
```
try:
print( 0 / 0)
except ZeroDivisionError:
print ("denominator can't be zero.")
finally:
print ("you handled exception very well")
```
output of above code
```
denominator can't be zero.
you handled exception very well
```