Download presentation
Presentation is loading. Please wait.
1
Exception Handling COSC 1323
2
Overview When Python runs into an error, it stops and displays an error message More precisely, it raises an exception Exceptions indicate something exceptional occurred and Python cannot continue Using exception handling, you can intercept and handle exceptions so that your program doesn’t end abruptly
3
Simple Exception Example
# try/except # try : num = float(input(“Enter a number: “) except : print(“Something went wrong”) else : print(“Number entered was %.2f” % num)
4
Specifying The Exception Type
# try/except try : num = float(input(“Enter a number: “) except ValueError: print(“That was not a number!”) else : print(“Number entered was %.2f” % num)
5
Getting an Exception’s Argument
try : num = float(input(“\nEnter a number “)) except ValueError as e : print(“That was not a number! Python says: “) print(e)
6
Some Exception Types IOError – Raised when an IO operation fails, such as when an attempt is made to open a nonexistent file in read mode IndexError – Raised when a sequence is indexed with a number of a nonexistent element. KeyError – Raised when a dictionary key is not found See page 207 of our book for more examples More Python Exceptions:
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.