EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could cause problems, and try to deal with them before the problems occur. In Java, we have exception handling, a powerful tool for ensuring program reliability. An error condition that occurs during program runtime is called an exception Exceptions are represented by exception objects, which are generated (thrown) in response to error conditions Java includes a rich set of routines for dealing with such circumstances: this is known as exception handling Java can do that either through: o Using try/catch blocks o Or if the code that could cause the exception is inside a method, then you can let that method throws an exception, and at the call block put the method s calling within try.. catch block. Catching exceptions through using try/catch block o Consists of try block followed by one or more catch blocks try block: encloses code that might throw an exception catch block(s) deal with any exception(s) thrown Syntax for try/catch block is as follows: // code that may throw an exception catch (ExceptionType parametername) { // code that handles an exception thrown in the try block o For catching exceptions: Statements in the try block are executed in sequence. When one of the statements throws an exception, control is passed to the matching catch block and statements inside the catch block are executed
Provided the catch block does not halt the program or return from the method, program execution continues at the first statement following the catch block If more than one exception is possible, multiple catch blocks can be written, but only one of them can be excused. If no error occurs then no exception is thrown, all statements in the try block are executed and the catch block(s) will be skipped Java Famous Exceptions: In Java Exception is a class with many descendants. o NullPointerException o ArrayIndexOutOfBoundsException o ClassCastException o RuntimeException o FileNotFoundException o ArithmeticException o IllegalArgumentException Why use an Exception? To tell the code using your method that something went wrong, so instead of showing the following message to the user o Exception in thread "main" java.lang.arrayindexoutofboundsexception: 5 at RuntimeException.main(RuntimeException.java:8) o You can build the following message Accessed index 5, which isn t in the array The method that called it was main Debugging and understanding control flow Source: here.
Check the following example. EXCEPTION HANDLING EXAMPLE public class Quotient { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers int number1 = input.nextint(); int number2 = input.nextint(); System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); We are expecting that we are dealing with smart user all the time and everything will be Ok. But that is not the case. Some weird cases could happen as follows: Imagine that the user input anything from the keyboard when s/he was asked to input the numbers. In this case you will have a run-time error and an exception called InputMismatchException will show up. Or imagine if the user input 0 as a second number. In this case you will have a run-time error and an exception called ArithmeticException will show up. Let s try to fix the problem above. public class QuotientWithIf { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers int number1 = input.nextint(); int number2 = input.nextint(); if (number2!= 0) System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); else System.out.println("Divisor cannot be zero ");
Here we solved the problem of division by zero, but we did not fix the other problem. Let s try to fix the same problem by building a method to do the division. public class QuotientWithMethod { public static int quotient(int number1, int number2) { if (number2 == 0) { System.out.println("Divisor cannot be zero"); System.exit(1); return number1 / number2; Scanner input = new Scanner(System.in); // Prompt the user to enter two integers int number1 = input.nextint(); int number2 = input.nextint(); int result = quotient(number1, number2); System.out.println(number1 + " / " + number2 + " is " + result); Here we solved the problem of division by zero, but we did not fix the other problem. Another problem is, if the user makes any mistake we did not give him/her the chance to re-input the data again. So here is a solution for all that. Let s use the try catch to solve the previous problems. public class QuotientWithException { boolean G = true; while (G==true) { number1 = input.nextint(); number2 = input.nextint(); number3= number1 / number2;
System.out.println(number1 + "/"+ number2 +" = "+ number3); G= false; catch (ArithmeticException E) { System.out.println("you cant divide by zero"); catch (InputMismatchException W) { System.out.println("you have to input number"); if (input.hasnext()) input.next(); // while // main // class Let s use throws with try catch to solve the method problem public class QuotientWithException { public static int quotient (int number1, int number2) throws ArithmeticException { return number1 / number2; boolean G = true; while (G==true) { number1 = input.nextint(); number2 = input.nextint(); number3= number1 / number2; System.out.println(number1 + "/"+ number2 +" = "+ number3); G= false; catch (ArithmeticException E) { System.out.println("you cant divide by zero"); catch (InputMismatchException W) { System.out.println("you have to input number"); if (input.hasnext()) input.next(); // while // main // class
Here is another way to get data from user then validate this Data. Here we let the user input anything as a string, then we validate this string to see if it is an integer/float/.etc. or not. We use a wrapper class to validate that. Check the following code. int value; // number to be supplied by user String input; // value read from keyboard Scanner kb = new Scanner (System.in); System.out.print ("Enter a number: "); input = kb.nextline(); value = Integer.parseInt(input); catch (NumberFormatException e) { System.out.println (input + "is not valid.\n" +"Please enter digits only.");