Exceptions
-
Exception Error Messages
You can associate a message with an exception when you raise it. Builtin exceptions often have messages associated with them already. To get the message when you catch the exception, just give it a name with the as keyword.
-
Catching Specific Exceptions
If it’s possible that some code may raise multiple different exceptions, we can catch the different types of exception separately. In this example, f_to_c() raises our custom NoInputError if no input is entered, or ValueError if input is entered but can’t be converted to a number. Output if no input entered: Output if text entered…
-
Catching Exceptions
Python programs consist of functions and methods that call each other. Information about which function calls which is stored in an area of memory that Python allocates known as the call stack. If an exception is raised you can catch the exception anywhere up the call stack. So if a function a() calls b() which…
-
Raising Exceptions
You can raise an exception in your Python code using the raise keyword. There are many predefined exceptions in Python. You can also create your own exceptions, typically by creating a subclass of the builtin Exception class. Here’s a program that calculates an area. If you pass negative values to the calculate_area function, it raises…
-
Exceptions Introduction
There are basically two different types of possible error in Python programs. The first type, and often the most difficult to deal with, are errors in your logic. The program works but it doesn’t do what you expect. Your Python is perfectly legitimate and the computer does exactly what you tell it to do, but…