Damian Gordon Exception Handling When an error occurs in a program that causes the program to crash we call that an exception since something exceptional has occurred We say that ID: 798733
Download The PPT/PDF document "Python: Exception Handling" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Python: Exception Handling
Damian Gordon
Slide2Exception Handling
When an error occurs in a program that causes the program to crash, we call that an “
exception
” (since something exceptional has occurred).
We say that “
Python raises an exception
” when an error occurs.
Slide3Exception Handling
What happens if we try to open a file that doesn’t exist?
Slide4Exception Handling
What happens if we try to open a file that doesn’t exist?
>>>
Traceback
(most recent call last):
File "C:\
Python34\FileRead.py
", line 3, in <module>
file_pointer
= open("C:\
Python34\MyDtaa.txt
", "r")
FileNotFoundError
: [
Errno
2] No such file or directory: 'C:\\Python34\\
MyDtaa.txt'
Slide5Exception Handling
Python has a way of intercepting the exceptions (and handling it) before the program crashes, and exiting gracefully.
Using the
try
and
except
commands.
Slide6Exception Handling
# PROGRAM
ExceptionHanding1
try:
file_pointer
= open("C:\Python34\FakeFile.txt", "r")
print(
file_pointer.read
())
file_pointer.close
()
except
:
print("Something went wrong
")
# END.
Slide7Exception Handling
# PROGRAM
ExceptionHanding1
try:
file_pointer
= open("C:\Python34\FakeFile.txt", "r")
print(
file_pointer.read
())
file_pointer.close
()
except
: print("Something went wrong") # END.
IF (There is no problem opening the file) THEN
ELSE
ENDIF;
END.
Slide8Exception Handling
If we are asking for the user to input the filename we want to open, it is very important that we include an exception handling block to make sure we deal with the case of the user typing in the wrong filename.
Slide9Exception Handling
# PROGRAM
ExceptionHandling2
NameOfFile
=
str
(input("What File would you like to read: "))
PathName
= "C:\\Python34\\"
Extension = ".txt"
FullFileName
=
PathName
+
NameOfFile + Extensionfile_pointer = open(
FullFileName, "r")print(
file_pointer.read())
file_pointer.close
()
# END.
Without the exception block
Slide10Exception Handling
# PROGRAM
ExceptionHandling2
NameOfFile
=
str
(input("What File would you like to read: "))
PathName
= "C:\\Python34\\"
Extension = ".txt"
FullFileName
=
PathName
+
NameOfFile + Extensiontry: file_pointer
= open(FullFileName, "r")
print(file_pointer.read
())
file_pointer.close
()
except:
print("No file of that name found")
# END.
With the exception block
Slide11Exception Handling
Python can detect different types of exceptions, including:
Input/Output
exceptions
File indexing exceptions
Directory key exceptions
Variable naming exceptions
Syntax exceptions
Type exceptions
Argument exceptions
Divide-by-zero exceptions
Slide12Exception Handling
Exception Type
Description
IOError
Raised when trying
to read or write a non-existent file
IndexError
Raised when an
array element that doesn’t exist is named
KeyError
Raised when a dictionary key is not found
NameError
Raised when the name of
variable or function is not found
SyntaxErrorRaised when a syntax error in the code is detectedTypeErrorRaised when an inappropriate type is detected
ValueErrorRaised when a problem with the value passed in is detected
ZeroDivisionErrorRaised when denominator of a division is zero
Slide13Exception Handling
# PROGRAM
ExceptionHandling3
try:
InputValue
=
int
(input("Please Input a Value: "))
print("The value input was",
InputValue
)
except
ValueError
: print("Dude, you didn't type in a number!")# END.
Slide14Exception Handling
# PROGRAM
ExceptionHandling3
try:
InputValue
=
int
(input("Please Input a Value: "))
print("The value input was",
InputValue
)
except
ValueError
: print("Dude, you didn't type in a number!")# END.
Checking for a ValueError.
Slide15Exception Handling
We can handle multiple exceptions together by listing them in a single
except
clause.
For example:
except(
TypeError
,
ValueError
):
Slide16Exception Handling
# PROGRAM
ExceptionHandling4
for
InputValue
in (None, "Hi!"):
# DO
try:
print(float(
InputValue
))
except(
TypeError
, ValueError): print("Something went wrong!")# ENDFOR;
# END.
Slide17Exception Handling
# PROGRAM
ExceptionHandling4
for
InputValue
in (None, "Hi!"):
# DO
try:
print(float(
InputValue
))
except(
TypeError
,
ValueError): print("Something went wrong!")# ENDFOR;
# END.
Checking for a TypeError and ValueError.
TypeError
: float(None)
ValueError
: float(“Hi!”)
Slide18Exception Handling
We can also handle multiple exceptions individually by listing them in a
seperate
except
clauses.
For example:
except
TypeError
:
except
ValueError
:
Slide19Exception Handling
# PROGRAM
ExceptionHandling5
for
InputValue
in (None, "Hi!"):
# DO
try:
print(float(
InputValue
))
except
TypeError
:
print("Type Error: Dude, you typed in a NULL value”) except
ValueError: print("Value Error: Dude, you typed in
characters")
# ENDFOR;
# END.
Slide20Exception Handling
# PROGRAM
ExceptionHandling5
for
InputValue
in (None, "Hi!"):
# DO
try:
print(float(
InputValue
))
except
TypeError
:
print("Type Error: Dude, you typed in a NULL value”) except
ValueError: print("Value Error: Dude, you typed in
characters")
# ENDFOR;
# END.
Checking for a
TypeError
and
ValueError
.
TypeError
: float(None)
ValueError
: float(“Hi!”)
Slide21Exception Handling
When an exception occurs, that exception passes a system message back to the program as well that can be printed out.
For example:
except
TypeError
as
SysMessage
:
print
("System Message:",
SysMessage
)
Slide22Exception Handling
# PROGRAM
ExceptionHandling6
for
InputValue
in (None, "Hi!"):
# DO
try:
print(float(
InputValue
))
except(
TypeError
,
ValueError) as SysMessage: print("Something went wrong!") print("System Message:",
SysMessage)
# ENDFOR;# END.
Slide23Exception Handling
# PROGRAM
ExceptionHandling6
for
InputValue
in (None, "Hi!"):
# DO
try:
print(float(
InputValue
))
except(
TypeError
,
ValueError) as SysMessage: print("Something went wrong!") print("System Message:",
SysMessage)
# ENDFOR;# END.
System Message:
float() argument must be a string or a number, not '
NoneType
'
System Message: could not convert string to float: 'Hi!'
Slide24Exception Handling
For can also add a single
else
statement to the
except
block.
This
else
statement is executed if no exceptions are raised in the
try
block.
Slide25Exception Handling
# PROGRAM
ExceptionHandling7
try:
InputValue
=
int
(input("Please Input a Value: "))
except
ValueError
:
print("Dude, you didn't type in a number!")
else:
print("The value input was", InputValue)# END.
Slide26Exception Handling
# PROGRAM
ExceptionHandling7
try:
InputValue
=
int
(input("Please Input a Value: "))
except
ValueError
:
print("Dude, you didn't type in a number!")
else:
print("The value input was", InputValue)# END.
An ELSE statement after the EXCEPT block allows the program to let the user know that the TRY statement suceeded.
Slide27etc.