We have covered Java exceptions in several places in the notes, but this section will collate some of the issues and discuss exceptions in some more detail. As you are aware exceptions are "problems" that occur at run-time, during a program's execution. In completing the exercises in the notes you will probably have suffered These exceptions indicate that there is something wrong with the code that you have written, with the error only apparent at run-time. However, there is a lot more to exceptions in Java than just these errors; the use of exceptions allow us to write robust code that is easier to follow. Not only that, but for the user trying to understand what went wrong with a program, a message such as "USB key is not present" is much more helpful than a message "system error". Here is an exception code example: String s = new String("12345"); try{ int x = (new Integer(s)).intValue(); System.out.println("We have succeeded."); x = x*x; System.out.println("The number squared is " + x); } catch(NumberFormatException e) { System.out.println("Invalid string for conversion to int."); } finally { System.out.println("We get here always!"); } This section of code can catch exceptions using a combination of
If we examine this block of code when everything goes correctly, such as when the string is We have succeeded. The number squared is 152399025 We get here always! Importantly, notice that we have displayed the "succeeded" message and that we have squared the value. The But if the string is Invalid string for conversion to int. We get here always! Notice this time that we do not get the message "We have succeeded" or do we attempt to convert the code. The execution point has jumped immediately from the construction of the How do we know that the constructor to Exceptions are very useful in that they improve the legibility of our code and allow us to recover from potentially fatal errors. |