All Java errors are handled as exceptions. Exceptions extend the base class, Exception. You might have seen the try and catch block used. This is a way to “catch” exceptions – this essentially allowing you to handle various unexpected errors gracefully.
Life isn’t perfect. Much as we’d like to think otherwise, sometimes we encounter exceptional behavior. Things like missing files, badly formatted data to be parsed, and operations on null things are just a few of the many exceptions you may meet in your programming career. When these things happen, the JVM throws a temper tantrum, or (more technically) throws an exception.
How do you know if an exception could be thrown? The hard way is when the compiler complains that you didn’t properly handle the method. The easy way involves the API documentation. The standard API documentation on the Java site begins a method’s documentation with its header: the access level, return type, method name, parameters, miscellaneous modifiers, and the declared exceptions. For example, the readLine method in class java.io.BufferedReader throws IOException. Its header looks like this:
If a method might throw an exception, it has to declare that exception in its header using the throws statement. (Note: just because a method declares an exception doesn’t mean that it willthrow it, just that it might.) If you use a risky method, you have to tell the compiler what to do in case something bad happens. This is called catching the exception.