Tuesday 4 February 2014

Exceptions

So this post is a little bit late... I had intended on posting it last week, but life gets in the way and other assignments take up more of my time. Anyway, last week we had to do an assignment as well as a lab in which we utilized a wonderful class known as exceptions. Now for those of you reading and who don't know what an exception class is, to put it simply, its errors. An example of an exception class that I think is the easiest to picture, would be the "ZeroDivisionError". This is an exception class that is flagged whenever the function for division encounters a denominator that is equal to zero. Now the really interesting and cool things about the exception class, is that like any other class, you can make your own! Now it probably doesn't seem that cool at first, but, through making your own unique exceptions, you can put in a few new levels of depth to any of the functions that you write. For example, lets say that you make a function that prints a "happy x birthday!" string. Naturally you would just have the user input an x and concatenate it to the string. Let's say somebody tries to mess around and inputs a negative number. Now it is impossible to have a negative age, so you can create your own exception, let's call it "NegativeAgeError", and raise it if x<=0. Now should someone try to input a negative number, not only will it not be accepted, but the user will be given information, in the form of an error (with a message if you so choose to add one, because you can), as to what they did in order to trigger an error. One last point about the exception class that I absolutely love, is that you can make your function work around the errors so that your program doesn't crash. Lets go back to the "ZeroDivisionError" just because its easy and I wish we could divide by zero. Anyway, let's say your function takes in user inputs for a denominator, and applies it to a specific numerator, and let's say the user chooses 0 as his denominator. Normally, this would cause the error to be raised and exit the program, however, if you so please, you can utilise the except command with the "ZeroDivisionError" as its argument in order to make it so that if that error should be triggered, your function ignores it and acts like nothing happened. Personally I love the idea of just pushing problems right under the rug.

Well that's it for what was supposed to be my rant last week on the exception class, which is by far now my favourite class(so far).

- Just a first year CS student.

No comments:

Post a Comment