This link is anonymous and does not include my personal links. https://file.io/D2JRztypavpe Exception Handling The Java exception
Question:
This link is anonymous and does not include my personal links.
https://file.io/D2JRztypavpe
Exception Handling
The Java exception mechanism is a way of handling errors and exceptional circumstances with minimal logic in your code. In a typical procedural language you must provide some kind of conditional code, such as anif...else...endifstructure orcasestructure to catch and deal with possible errors. This can force the creation of long, complex code. The exception mechanism allows you to write your code as though it execute without problems (i.e. without conditional structures), and uses separate exception handlers to deal with errors and exceptions that may arise during execution. Java'sThrowableclass is the parent ofErrorandException, and these are the base classes for handling exceptions and errors. You can also write your own exception classes.
Exceptions can be caught and handled using thetry...catch...finallyconstruct. The base program is placed in thetryblock, error and exception handling is placed in thecatchblock, and finishing up code to be run whether exceptions take place or not is placed in thefinallyblock.
All exceptions can be caught using thecatch(Exceptione)block. Once caught, information about the exception can be printed out, as in the sample classLab04given at the bottom of this lab. You can also catch specific exceptions, as in this example:
try { ... } catch( NumberFormatException e ) { ... code to handle specific exception } catch( ArrayIndexOutOfBoundsException e ) { ... code to handle specific exception }
Any number of distinct exceptions can be handled with multiplecatchblocks. Note that order is important. In the following example:
try { ... } catch( Exception e ) { ... code to handle specific exception } catch( NumberFormatException e ) { ... code to handle specific exception }
the specificNumberFormatExceptionwill never be caught because all exceptions are caught by the generic exception handlerExceptionfirst.
The following code catches any exception generated during program execution and prints messages for those exceptions. Attempt to create a number of different errors (e.g. division by zero, file not found), and see the names of the actual exceptions that occur. Note the differences in output between the calls togetMessage(),getLocalizedMessages(), andprintStackTrace().
package cp213; public class ExceptionTest { public static void main(String[] args) { try { // insert bad code here } catch (Exception e) { // generic exception/error catching System.err.println("Caught Exception"); System.err.println("getMessage():" + e.getMessage()); System.err.println("getLocalizedMessage():" + e.getLocalizedMessage()); System.err.println("toString():" + e); System.err.println("printStackTrace():"); e.printStackTrace(); } finally { // code to always be executed when try block ends System.out.println("End of program"); } } }
Given the different types of errors you have discovered, rewrite this code to generate and catch specific errors and give appropriate error messages for each. How many different errors can you generate?
Eclipse has an option that makes finding and catching mandatory exceptions very easy. Enter the following code into a Java method:
Scanner x = new Scanner( new File("output.txt") );
Eclipse highlights this code as having an error:
Unhandled exception type FileNotFoundException
At this point you could enter atry...catchblock by hand to eliminate the error. Instead, highlight the offending code, right click on it and chooseSurround With / Try/Catch Block. Eclipse then generates the following code:
try { Scanner x = new Scanner( new File("output.txt") ); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }
You can then replace theTODOcomment orprintStackTrace()code with your own code. If there are multiple mandatory exceptions Eclipse gives each its owncatchblock in the proper order.
Custom Exceptions
You can write your own exceptions that extend existing exception classes. This allows you to provide increased functionality within the custom exception class. For example, an exception can print an error message, or save a record in an error log. The following class defines a simple custom exception for dealing with invalid input integers:
package cp213; @SuppressWarnings("serial") public class BadValueException extends Exception { int a, b; public BadValueException(int a, int b) { // Call parent constructor to define message. super("Value not in range " + a + " to " + b); this.a = a; this.b = b; } }
BadValueExceptioncan be explicitly thrown by any method, as in this modified version of the method given earlier:
public static void main(String[] args) { final int first = 1; final int last = 100; Scanner keyboard = new Scanner(System.in); int total = 0; int x = 1; while (x != 0) { System.out.print("Enter an integer from " + first + " to " + last + " (0 to stop): "); try { x = keyboard.nextInt(); if (x < first || x > last) { // Explicitly throw an exception. throw new BadValueException(first, last); } else { total += x; } } catch (BadValueException e) { System.err.println(e.toString()); } catch (InputMismatchException e) { System.out.println("That is not an integer!"); keyboard.next(); // Get rid of offending value. } } keyboard.close(); System.out.println("Total: " + total); }