Algorithms and OOD (CSC 207 2014F) : EBoards

CSC207.01 2014F, Class 14: Interfaces and Polymorphism




Upcoming Work

Extra Credit Opportunities


Peer Support



Quick Notes on Exceptions

When should I declare that my procedure throws exceptions?

When you note that there is a possibility that your procedure can fail.

Can't every procedure fail?

There are procedures that never fail if their preconditions are met.

There are procedures whose failure is conceptually so rare that it's not worth indicating.

And there are certainly some procedures that should never fail. If I'm writing a sort(int[] arr) method, there aren't any clear cases in which it should fail.

When should I throw an exception?

When you've identified that an error has occured.

When should I use a try/catch clause?

When you are calling code that can fail and there is something you can reasonably do in reaction to the exception. For example, you might do an alternate computation, you might want to log an error, or you might want to throw a different exception.

When should I simply pass along exceptions?

When the failure of a method you are calling will cause your method to fail, and you consider it appropriate for your client to get the same exception that you got. I'll note that it's rare that code simply passes along exceptions. (It's an exception to pass exceptions.)

Why don't I have to catch ClassCastException and ArrayIndexOutOfBounds exceptions?

Java has a set of exceptions that they call RuntimeExceptions. These need not be caught, but can be caught. I think the designers decided the forcing programmers to catch these would mostly clog up code and frustrate competent programmers who would never do things that would never result in such exceptions.

Questions on Interfaces and Polymorphism