Join Peggy Fisher for an in-depth discussion in this video Handling errors, part of Learning Java 8.
- Most programming languages have code that helps handle unexpected errors. It provides the programmer control over the exception so they can provide meaningful messages and avoid program interruptions. As you saw when we were working on our file examples, we added a try-catch block of code to handle a file exception error. We placed this in our code in areas that might cause an exception. When an error occurs, an exception is thrown, or raised, which is then caught by the exception handler.
The exception handler can be used for catching file errors as well as some logic errors. For example, divide by 0. Let's take a look. I have open here an error handling project. I start out by declaring count as 0. My intentions were that count would be the number of values that I'm adding up, so I can find the average. But as you can see, I forgot to ever add anything to count. I declare x, y, and z as integer values, I add them together and divide by count, and put that value into average, and then I print it out.
You can also see that there's no errors for the compiler; the syntax for this program is correct. But let's run it. Okay. We knew that divide by 0 was going to cause problems, and it did. You can see by the red error message, if I read the message, it says, "Exception in thread 'main' java.lang.ArithmeticException: "/ by zero at errorhandling.Errorhandling.main". Now this is a nice feature. My program is very small, but if it was large, if I click on the blue ErrorHandling.java:18, it'll take me right to that line in my source code.
So it helps to identify exactly where the error occurred. Okay. Let's see if we can add some error handling logic so we don't get this ugly red message. If I add a try with an open curly bracket to indicate the start of the block of code, and I only calculate the average and print the average when there's no error, I can add a catch statement. The catch will help me handle any unexpected exceptions. So I type in the word Exception e.
Now e is an object that has information about what the error is, so I'm going to print out e. So I'm going to do System.out.println, and I'm going to print out e.toString. Okay. This time, if I run the exact same program without changing anything, I'll still get an error message, but it will not cause my program to end abruptly. As you can see, this time I did not get an unhandled exception, but I do have an error message telling me that there was an arithmetic exception, and that I'm trying to divide by zero.
You can use error handling in almost any program, and it is really helpful to avoid having your program end abruptly.
- Downloading and exploring NetBeans
- Understanding Java basics: data types, strings, arrays, and more
- Controlling flow with functions and loops
- Creating classes
- Sorting and searching arrays
- Manipulating files
- Handling errors
- Building GUIs