The Python Class/Exceptions

What makes up an exception?
All exceptions have to be derived from. In an analogy, this could be the world. There are 4-5 derivatives of, which are  ,  ,   and a few others that are exit exceptions.

When you use the  of a try/except, it will intercept any exceptions of the exceptions type and in the sub exceptions. This is useful because if you wanted to stop all error exceptions, you would use. However, this also blocks SystemExit (run by ) and KeyboardInterrupt (activated by doing Ctrl/Cmd/...+C), which we would not want to block because then the program could not exit automatically (you would have to click on the x).

We could do, and this is perfect because you can still exit, but it will not let any errors such as ValueErrors stop your program.

If we only want to block all ValueErrors, we would just do. This matters because when you make your own exceptions, you dont want your exception to be stopped by other exceptions (most of the time).

Creating a custom exception
When we create a class, in order to make it an exception, we need to make it a subclass of an existing class. This is where the parentheses come in. You can either define classes as or However, a parent class can go into the parentheses to make it a subclass. In an exception, it would be Now, if we were to try raising the x without the Exception, we would get. If we were to raise the one with the exception, we would get Traceback (most recent call last): File " ", line 1, in __main__.x

Giving it a message
Sure, if properly named, your exception might help. However, you might want to include an error message or pass variable values in to help the user figure out the problem. To do this, we have to access the exception's. We pass in our message in our own  function. Now if we were to raise x it would say: Traceback (most recent call last): File " ", line 1, in __main__.x: This is a test It now has a message.

Sub-classing another exception
To subclass another exception, just replace x with the Exception's class. For example, if we wanted to make y, we would write

Why would we subclass?
Subclassing is a good idea because then you can skip only the exceptions that come with certain operations, such as file reading. Let's make an exception that will raise if a file is too big. If we wanted to make a program that will skip all OS errors, including this one if there are any problems, we would write.