Monday, January 28, 2013

throws FileNotFoundException

throws FileNotFoundException explained (sort of):

An exception is an error that occurs at runtime. It is a response to unexpected condition or it is generated as a result of your executing a throw statement.


  • Checked exceptions: an exception that is a user error or a problem that cannot be foreseen by the programmer. Ex: If the file is to be opened but cannot be seen, exception occurs. These exceptions cannot be ignored at the time of compilation.
  • Runtime exceptions: an exception that could have been avoided by the programmer. Unlike checked exceptions, runtime exceptions can be ignored at the time of compilation.
  • Errors: These are not exceptions at all, but problems that arise beyond the control of the programmer. Errors are typically ignored because you can't do anything about them. If a stack overflow (overflow of memory in the parameters/preconceived memory) occurs, an error will rise. These are ignored at the time of compilation.
Hierarchy:

Throwable:
  • Error
  • Exception
    • IO Exception
    • RuntimeException
A really good example:

Let's look at the throw statement in context. The following pop method is taken from a class that implements a common stack object. The method removes the top element from the stack and returns the object.
public Object pop() {
    Object obj;

    if (size == 0) {
        throw new EmptyStackException();
    }

    obj = objectAt(size - 1);
    setObjectAt(size - 1, null);
    size--;
    return obj;
}
The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0),pop instantiates a new EmptyStackException object (a member of java.util) and throws it.



No comments:

Post a Comment