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 problems.
There are three general categories of errors that programmers handle: “erroneous data input from the user”, “common runtime errors”, and what is best described in the Java programming language as "checked exceptions".
What you will mainly focus on for this IA is erroneous data input from the user, both by using if/else blocks to try to nab problematic input, and even better, by limiting user input to appropriate data by the use of combo boxes etc.
But in certain situations, you will need to work with the other two, more sophisticated, categories of Java exception handling. This page includes lots of details about them for those who want to go a little bit further with this.
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 either Java compile time errors Java runtime errors (see sections III and IV below).
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. And in fact, this way the IB moderator 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”.
So though you can use the Try/Catch/Throw structure, you can also do something more traditional, with if/else blocks, 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 < 1 || grade > 7){ jOptionPane2.showInputDialog(null,"Please re-enter your number correctly."));
} else{ StudentRecord[k].setGrade(grade); }
Note that you may very well have lots of situations like these, especially if you have a lot of textField entry etc.
This is actually more error prevention than error handling, but it certainly is a major, and great, 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.
Here is a simple example. There is simply no way a grade outside of the range of 1, 2, 3, 4, 5, 6, 7 can be entered!!
So, though you can certainly make ample use of this water-tight form of error preventions, do try to include other error handling, as described on this page, also.
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 including 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.
For example, 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.
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.
For this category of errors, you will also use Java’s built in “Try & Catch” error handling capabilities. Though, in this case, 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 may likely encounter that will require Java runtime exception handling. It would be great if you could include one example of each, 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 runtime errors 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, if your array is of an Object type, the elements are intantiated before you try to access them. The error happens frequently when the array itself is initialized, but the elements of the array are not yet intantiated.
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 here is being treated as an object) 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 an integer is needed, but real number is sent.
Here is a straight-forward example.
public void aMethod(){ try{ int input = Integer.parseInt(br.readLine()); } catch(NumberFormatException ex){ jOptionPane1.showMessageDialog(this, "You need to input an integer (no decimal places possible), and you did not. Try again."); } }
With all of the above, note that you will also be preventing input errors by using simple if/else structures, as well as by limiting user input via combo box etc. - see the last two sections, below.
Documenting Your Exception/Error Handling
There is no official "Exception Handling" criterion with this IA, but you should have anticipated at least a bit of error handling in your planning stages.
You would not have necessarily anticipated lots of specific error handling situations that came up as your programming progressed, but in your evaluation, feel free to to make mention of them.
Plus, in your video, you will want to quickly show/note a few different examples of your error handling - don't just show the program working when perfect data is entered, also show what happens when erroneous data is input. So you could show things like JOptionPane pop-ups, which you can just trigger with the appropriate error, and you could also quickly show other try/catch situations, in the code itself.