Skip to main content
EduEquity - Free A Level & GCSE Resources
View All
Search
Shelves
Books
Log in
Info
Content
Books
[Concepts] Paper 4
CHAPTER 15: EXCEPTION ...
CHAPTER 15: EXCEPTION HANDLING
15.1 TRY-EXCEPT
15.1.1 Basic Structure
<PYTHON>
try
:
result =
10
/
0
except
ZeroDivisionError
:
print
(
"Cannot divide by zero"
)
15.1.2 Multiple Exceptions
<PYTHON>
try
:
file
=
open
(
"data.txt"
,
"r"
)
data =
int
(
file
.read())
except
FileNotFoundError
:
print
(
"File not found"
)
except
ValueError
:
print
(
"Invalid number"
)
15.1.3 Finally Block
<PYTHON>
try
:
file
=
open
(
"data.txt"
,
"r"
)
content =
file
.read()
except
FileNotFoundError
:
print
(
"File not found"
)
finally
:
if
'file'
in
locals
():
file
.close()
15.1.4 Raising Exceptions
<PYTHON>
def
divide
(
a
,
b
):
if
b ==
0
:
raise
ValueError
(
"Cannot divide by zero"
)
return
a / b
try
:
result = divide(
10
,
0
)
except
ValueError
as
e:
print
(e)
Enter section select mode
Previous
CHAPTER 14: FILE PROCESSING
Next
[Python] Important Algorithms
Back to top