Logout

Criterion P - Exception Handling and Examples

You need to think of how your program will be used, and what the most common "mis-uses" of it will be. And then for each one of them, come up with a solution to prevent that mis-use from causing too many problems.

What type of error handing should you include in your program? According to the former IB dossier criteria which focused much more on this, there are three general categories of errors that you need to handle, “common runtime errors”, “erroneous data input from the user”, and what is best described in the Java programming language as Checked Exceptions.

 

I. Java Checked Exceptions
Java Checked Exceptions are exceptions that can be analyzed by the Java compiler.  So if they are thrown, you won’t be able to compile without first includinga try & catch block. And you’ll note that these exceptions are automatically thrown by input and output methods that we use, such as BufferedReader.readLine(). So, in fact, for your program to compile at all, you’ll need basic try/catch blocks for all your input and output methods. (And so, yes, to get back to the way the IB dossier criteria describes them, the main checked exceptions you will be worried about could indeed be referred to as “data-file errors”.)
So, for example (given that you included the line: import java.io.*) if you try a few lines like:

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String s = input.readLine();
System.out.println(s);

You’ll get an error back that goes something like:
“unreported exception java.io.IOException; must be caught or declared to be thrown.”

So you have no choice but to put these lines within a try, and then do a catch. Or (see the box below) have Netbeans automatically do it for you. Either way, you should end up with something like this:


try {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    String s = input.readLine();
    System.out.println(s);
}catch (IOException ex) {
    ex.printStackTrace();
}

Your reading and writing methods are two sure places to look for examples. So in this section of your dossier you’ll mention both of these. (See later on in this section for details of how exactly to do that.)

Netbeans Auto-Try&Catch Feature

To make error handling even easier, you can use Netbeans’ automatic Try&Catch capability. Simply select the section of code that includes either input or output - though nothing more - and choose the “Surround with try-catch” item in the “Source” menu.

  

 

II. Common Runtime Error Handling
Also for this category of errors, you will use Java’s built in “Try & Catch” error handling capabilities; if you don’t, your program will compile, but it may not work properly when run (hence the term “runtime errors”.)

There are several situations you will likely encounter that will require Java runtime exception handling. It would be great if you could include one example of each in your write-up, but if your program does not need several different kinds of runtime error handling, then including multiple examples of the kinds you do use, is just as good.

Common Runtime Exceptions & How To Handle Them:


ArithmeticException

One of the most common ones you’ll experience is trying to divide by zero. Note how you can explicitly “throw” an exception to the nearest catch block.


private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
    int x = Integer.parseInt(jTextField1.getText());
    try{
        if(x == 0){
            throw new ArithmeticException("You can't divide by zero; please re-enter ");
        }
        int y = 3333/x;  //so if x!=0, you perform the division
    }
    catch(Exception e){
        jOptionPane1.showMessageDialog(this, e.getMessage());
        e.printStackTrace();  //this is to assist you the programmer as you test run the program.
    }
}

 

ArrayIndexOutOfBoundsException

If you have arrays - as you likely will - this is easily implemented. It checks to see if the index you are trying to access actually exists. If you use an index outside of the proper range, such as the common error of trying to access the array element with the number equal to (not one less than) the length of your array, then the exception will be thrown.


private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
try{ int[] zzz = {1,2,3};  //so the minimum element is [0] and the maximum element is [2] int z = Integer.parseInt(jTextField3.getText()); if(z > 2 || z < 0){ throw new ArrayIndexOutOfBoundsException("You can't have a negative array element, or one above the maximum number of elements"); } int blah = zzz[z];  //if within the proper index range, proceed with whatever }
catch(Exception eee){ jOptionPane2.showMessageDialog(this, eee.getMessage()); eee.printStackTrace(); //this is to assist you the programmer as you test run the program. } }

 

NullPointerException

Also associated with arrays, this is a great way to assure that your array elements are initialized before you try to access them. The error happens frequently when the array identifier itself is initialized, but the elements of the array are not yet initialized.


private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
    try{
        String[] sArray = new String[3]; //the array itself is initialized, but not yet its elements
        String x = jTextField2.getText();
        if( x.equals("yes")){
            sArray[0] = "Hello";
            sArray[1] = "World";
            sArray[2] = "How are you?";
        }
        else{
            throw new NullPointerException("You didn't initialize the elements of the array; the array itself yes, but not it's elements.");
        }
        String ssss = sArray[2];
    }
catch(Exception elephant){ jOptionPane1.showMessageDialog(this, elephant.getMessage()); elephant.printStackTrace(); //this is to assist you the programmer as you test run program. } }


NumberFormatException

This is common when a int is needed, but an double or long is sent.

See Morelli Chapter 11 (starting on page 492) for more details on, but here is a straight-forward example.


public void aMethod(){

    try{
        int input = Integer.parseInt(br.readLiine());
    }

    catch(NumberFormatException ex){
        jOptionPane1.showMessageDialog(this, "You need to input an integer (no decimal places possible), and you did not. Try again.");
    }
}

And note that you can’t just have Java Exception Handling, you must also use and document straight-forward error handling with if else statements.

Also note that you can prevent input errors by limiting user interaction to a list presented in a combo box etc. Though this is not programming error handling, it is error prevention none-the-less, and should be noted in this section.

 

 

III. Handling (other) Erroneous data input from the user with Code

Here we’re dealing with situations where erroneous data input by your user will cause logic errors with your program. But the erroneous data input will not cause Java runtime errors - as in the situations noted in section II. Nor will they have triggered checked exception issues at compile time, as noted in section I.

To handle this type of error you could also use “Try & Catch” blocks of Java, but you are not forced to. So you might as well error handle the old fashioned way for these cases, with conditional clauses that will pick up any erroneous input, and then prompt the user to re-enter. This way the IB marker is sure you are actually thinking through the error handling situation, and not just putting in auto-generated Try&Catch blocks.

Here are some examples of erroneous data input:
- You want the user to enter in a grade in the range of A - D or F, and they input another letter.
- You want the user to enter in a number grade in the range of 0 - 100, but they enter in a negative number or a number greater than 100.
- You want the user to type in “yes” or “no”, and they type in some other word like “maybe”, or they incorrectly input “y”.

Though you can use the Try/Catch/Throw structure, you could also do something more traditional, as this code fragment example demonstrates:


jLabel1.setText(“Input a grade (e.g. 85.3)”);
String inputString = jTextField1.getText();
double grade = Double.parseDouble(inputString);
if(grade < 0 || grade > 100){ jOptionPane2.showInputDialog(null,"Please re-enter your number correctly."));
} else{ StudentRecord[k].setGrade(grade); }

*** You may very well have lots of situations like these.***

Whether or not you use the traditional way or the Try/Throw/Catch way, situations like this should be handled and then written up in this section of your dossier. Read on for guidance of how to do this.

 

 

IV. Handling (other) Erroneous data input from the user with GUI Elements

This is actually more error prevention than error handling, but it certainly is a major way to deal with potential improper input by the user; you simply limit the data which can be input to be valid data, and you do this with GUI drop-down menus and the like.

So, read on, but as you can imagine, for this section, you will do (timed) screen shots with Grab etc. for each situation where you limit user input with a GUI object. You’ll paste those screen shots here, and add brief explanations of how each works, and why it suits the program.

***SL Note:  You may have to be creative coming up with lots of error handling. These last two categories could be the main one you use, and that’s perfectly fine.

 

 

Documenting Your Exception/Error Handling

Many specific error handling situations you likely did not anticipate in your planning stages, but in your evaluation, you can refer to these as specific implementations of general error handling.

You should also, in your video, show/note a few different examples of your error handling. Things like JOptionPane pop-ups, you can just trigger with the appropriate error, and other try/catch situations, you could show in the code itself.