image
image
image

Chapter 5: Exception Handling

image

As you get to working on your code, you may find there are some times when you will need to work with exceptions inside the code. This may be confusing for the beginner, but it is really important to learn how to handle these so that you can go around them, or at least not have the program close down when the exception is raised by the computer. In some cases, you are able to raise some of your own exceptions, even if they are seen as normal by the compiler, based on what you would like to have happen inside our code. Let’s take a look at how exception handling and how you can deal with them in your code.

If there is an abnormal condition that is going on with your code, either ones that the compiler automatically recognizes or you set up for your program, you will need to use the idea of exceptions in this code. As mentioned, there are a few of these conditions that the compiler and the code won’t allow you to do. For example, if you add in the wrong statement to the code, you misspell some of the words and it can’t find the function or variable that you want, or you try to divide by zero, you may find that the interpreter is not able to handle the request and an exception is raised.

In addition, there are some times when you decide that the program or application you are working on should have a new exception. This one may be seen as fine by the interpreter, but for what you would like the program to do, you want to make sure that the code raises up an exception. For example, you may be working on a website that is only going to allow users who are 18 or older onto it. You could raise an exception that comes up when the user puts their age in as under 18 so that the program knows how to handle this.

As you are going through the Python program, take a look through the library that is in there and you are sure to notice that the exceptions are already present in there. This can help you to write your code a lot better because you will be able to bring them out and use them as you wish. One of the exceptions that you are sure to run into at some point and which are already in the Python library includes when you try to divide by zero or when you try to read to a point that is past the end of your file.

In some cases, you may want to allow these things to happen and this is where exception handling will come in. If you try to divide by zero for example and you don’t work on exception handling, you are just going to have an error that will just close down the program. This isn’t the best idea when you are working on a new code; you usually want something to show up rather than the computer just giving up. With the help of exception handling, you will be able to tell the computer to write out a message, such as “you are trying to divide by zero!” so that the user knows what they are doing wrong, rather than just feeling that something is wrong with the computer.

As we talked about a bit before, it is also possible for you to make up some of your own exceptions, even if this is not included in the library of Python. While the code may trigger the exception in some cases, such as when it sees an error, there are times that you will be able to set these errors up yourself and you can even determine how the compiler is going to react when these errors come up.

When you decide to work with exceptions inside of your code, there are several that are already going to be found inside the library for Python. You should take a look at these and learn how they will interfere with the code that you are trying to write. Some of the exception statements that you may find inside of Python include:

How do I raise an exception?

So now that we have taken some time to talk about exceptions and what they mean inside the Python code, it is time to take a look at how you would raise these inside of your code. Any time that you notice there is an issue inside the code and the program is attempting to do things that seem wrong, or aren’t going to work based on how Python is laid out, your compiler is going to raise an exception about this conduct. This is due to the fact that your program is not able to figure out what it should do in these situations. Sometimes there may just be a simple issue with finding a file that you typed in the wrong name for and other times it could be something like trying to divide by zero that will raise this exception.

A good example of what will happen when your compiler tries to raise an exception includes the following example:

x=10

y=10

result=x/y #trying to divide by zero

print(result)

The output that you are going to get when you try to get the interpreter to go through this code would be:

>>>

Traceback (most recent call last):

File “D:\Python34\tt.py”, line 3, in <module>

Result=x/y

ZeroDivisionError: division by zero

>>>

In this example, your program is going to raise up the error because the code that you wrote out is trying to divide by zero, something that isn’t allowed inside the Python language so you will end up getting the error. Now, when you are trying to run the program, you are not likely to want to see error messages showing up all the time because it looks messy and can turn the user off from taking a look at the code.

Luckily, there are some options that you can try out that will add in something to the code and gives you the option of adding in something else, other than the error message, any time that these exceptions happen. You could add in a different message to the box that comes up during the exception or you may even be able to still move the code along another way.

You will notice that having a message show up on the screen will make things easier to deal with and can seem a bit friendlier to others who are trying to take a look at the code. It also helps them to understand why the exception is raised and may even help them to fix the issues a bit easier. A good example of what you would do when you want to change up the message when an exception happens includes:

X=10

y=0

result=0

try:

result=x/y

print(result)

except ZeroDivisionError:

print(“You are trying to divide by zero.”)

As you should be able to see from this code, it is pretty similar to the one that we used above, but there is a simple change in it. With this code, you will still see the error come up, but you will be able to avoid the output that is above and instead you will get a simple message to come up. This message is going to be “you are trying to divide by zero” or some other message that you placed into this area. This shows the user what is going on with the error and let’s them figure out how to make changes so that the code will keep going through and the error will be fixed.

Defining some of your own exceptions

With the example that we looked at above, we were discussing what happens when the compiler sees and error that it isn’t able to handle. But sometimes you will write out a code that will need some special exceptions to help it work properly. These exceptions may seem like they will work just fine inside of the compiler but because of the code that you are trying to write, you want to raise these errors based on the answers that the user gives you.

For example, there may be times inside of your code when you don’t want the user to input some numbers and you will be able to make an exception for this. You may have a game that you are working on and you don’t want to allow your user to guess more than two or three times, you can create an exception that is able to handle this. Allowing the user to make unlimited guesses would be fine with the compiler, but usually you want to keep this to a minimum to save time and move the program along and using the exceptions will help you to do this.

You are able to create the rules that are going to dictate the exceptions that are in your code. Any time that you want to create an abnormal situation for the code you will just need to add in the right exception to make this happen. Here is an example of how you would create some of your own exceptions inside of this language:

class CustomException(Exception):

def_init_(self, value):

self.parameter=value

def_str_(self):

return repr(self.parameter)

try:

raise CustomException(“This is a CustomError!”)

except CustomException as ex:

print(“Caught:”, ex.parameter)

Inside of this code, you have set up one of your own exceptions and the message “Caught: This is a CustomError!” is what will show up when you, or even the user, places in the information that sets off the error. This is a good way to show your custom exception inside the program, especially if it is something that you want just for the program, and not an exception that is particular to Python.

In this example, we just used some generic wording for the exception that was brought up, but you will be able to change things around and get it to say whatever you would like. You can name the exception that is going on, say something like “You have to be 18 to use this program,” or have something else that will go into this point.

There are just so many things that you are able to do with exceptions, whether you are raising them in your own code or you are trying to use the ones that are already available inside of Python to help you out. There are even cases when you are able to bring up more than one exception at a time depending on the program that you are working on. Give some of these codes a chance and put them into the compiler to get the hang of it and to see how each of these will work when working on exceptions.