Computer Science Canada [Tutorial] Exception Handling |
Author: | rizzix [ Thu Jun 26, 2003 9:05 pm ] | ||||||||||
Post subject: | [Tutorial] Exception Handling | ||||||||||
Exceptions are used in java as a way to identify errors in your code. An exception is an object that is raised/thrown if something is goes wrong. If an exception is thrown, it has to be dealt with. There are 2 way you can deal with exceptions... 1] throw it again or 2] catch it One way or the other finally the exception will be caught. If you don't catch it the Java Virtual Machine will, and will force your program to stop execution. Any code that is to throw an exception should be put in a try block:
note: we haven't dealt with the exception yet. the void Thread.sleep(int msec); method pauses your program to sleep for the given milliseconds. It throws an InterruptedException if it receives an interrupt signal. Lets not worry how it works for now, but keep in mind that it throws an exception. Here is how we catch this exception:
we caught the exception and printed it's message. Note that we caught the exception of type Exception. All Exception objects that are thrown are inherited from this class. As soon as an exception is thrown execution jumps to the nearest catch block that can handle that exception. That is statement4 is never executed if an exception is thrown. To be more specific, we could have also caught the exception as of type InterruptedException:
if this code was in a method, we could have re-thrown the exception if we want the calling code to handle it like this:
note: we use the throws keyword followed by the type of exception it throws to denote that the method throws that exception! the calling code must handle that exception that is thrown, else the JVM will catch it and stop execution of your program. If an exception is thrown, statements after the statement that throws the exception are not executed. But sometimes you may need to execute some code anyhow whether an exception is thrown or not. You can do it buy adding a finally block. When dealing with objects that deal with files, you will need to close the object even after an exception occurs, this is an example of when we use the finally block.
if the code you are catching exception for throws multiple exceptions you can enclose all that code in a single try block, and write multiple catch block with different exception types as its arguments, thus handling each exception separately. |