The most common and effective way to report errors in Python is by generating your own exceptions. The "raise" statement is used to generate exceptions.
- [Instructor] Exceptions are an excellent way to report runtime errors. You can generate your own exceptions for error reporting in your code, and this is considered best practice. Here in Komodo, I've opened a working copy of exceptions.py from chapter 10 of the exercise files, and you'll notice, if you've been following along in order that this is our inclusive range example from the functions chapter, and here, in the initializing parameters section, if I have the wrong number of arguments, either less than one or more than three, then I generate an exception using the raise statement.
So I raise and I give the error the exception class, in this case is TypeError, which is recommended for this type of an error, and down here when I run it, I have the correct number of arguments here so if I run this, you see I get the result I expect, but if I have no arguments I get this exception, it says, TypeError and you notice I have a hole trace back here, exactly as we would expect. Or if I give it too many arguments, and run that, I get the message that I had too many arguments.
Now, of course, I can catch this, just like I would with any exception by using try, and I'll put all of this in the try block, and then I say except, and this is a TypeError, I can say as e: to get the error message, and then I can print range error: and the message.
And now when I run it, I get range error, expected at most three arguments, etc. So this working exactly as I expected. Exceptions are a convenient and useful way to report errors from your own functions and classes.
- Python anatomy
- Types and values
- Conditionals and operators
- Building loops
- Defining functions
- Python data structures: lists, tuples, sets, and more
- Creating classes
- Handling exceptions
- Working with strings
- File input/output (I/O)
- Creating modules
- Integrating a database with Python db-api
Skill Level Intermediate
Python: Programming Efficientlywith Michele Vallisneri2h 15m Intermediate
2. Language Overview
3. Types and Values
8. Structured Data
11. String Objects
12. File I/O
13. Built-in Functions
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.