In this tutorial, I am giving an example of exception handling in Java. Learn how to handle an exception in the Java program using the try-catch
block.
In the below example, numbers get passed in from the command line and are summed. Because command-line arguments get passed in as strings, it is necessary to convert the strings to numbers. This is done with the parseInt()
method of the Integer
class. Given a string, we convert it to an int:
int number = Integer.parseInt("1234");
Under normal circumstances, users will pass in numbers, and everything will work fine. But a NumberFormatException
will be thrown if a non-numeric string value is passed in. By not putting parseInt()
call within a try-catch
block, the program will still compile and run because NumberFormatException
is a runtime exception.
Without the try-catch
block, the program stops if the exception happens, because there is nothing to catch the exception. However, NumeberFormatException
is a runtime exception and isn't required to be in a try-catch
block. Assuming you don't want the program to stop, you need the try-catch
block to watch for non-numerical string input.
Java Exception Handling Example
The complete code for just such a try-catch
block is given below.
// DoSum.java public class DoSum { public static void main(String args[]) { long answer = 0; int number; for(int i=0; i< args.length; i++) { try { number = Integer.parseInt(args[i]); answer += number; } catch (NumberFormatException nfe) { System.err.println("Unable to convert " + args[i]); } } System.out.println("The sum is " + answer); } }
Test by Passing Integer Values
java DoSum 3 5 9
Output
The sum is 17
Test by Passing Integer with String to Raise Error
java DoSum 2 a 9
Output
Unable to convert a The sum is 11
If a non-numerical string is passed into the parseInt()
method, the NumberFormatException
is thrown. The answer +=
number; the line is never reached for that pass through the for-loop
; instead, the program jumps to the catch
clause. Because of the exception type matches the one found in the catch clause, the code within the catch
clause block is executed, displaying the error message.
Once compiled, you can run the program and pass in numbers to get their sum, or numbers and strings to get the sum of the numbers with the non-numerical string ignored.