import java.util.InputMismatchException; import java.util.Scanner; /** * * @author AChapin */ public class ExceptionExamples { // just explicitly throw an Exception public static void thrower() throws BadThingHappened { throw new BadThingHappened(); } // return string based on number for day of the week // throw a tantrum if you get bad parameters public static String dayOfWeek(int n) { if (n < 0 || n > 6) { throw new IllegalArgumentException("Invalid day of week: " + n); } return (new String[]{"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"})[n]; } // force a null pointer exception public static void badPointer() { System.out.println("in badPointer"); String bad = null; bad.equals("bad"); } // Force an out of bounds exception public static void badArray() { System.out.println("in badArray"); int list[] = new int[5]; list[27] = 4; } // get stack information from exception and control output public static void exceptionOutput(Exception ex) { // exceptions can print stack themselves // print to System.err may result in // different format, different location, or not show up at all... System.err.println("Normal Stack Trace"); ex.printStackTrace(); // get array of lines in the stack StackTraceElement[] stack = ex.getStackTrace(); // build up string of stack trace lines String out = "\t"; for (int i = stack.length - 1; i >= 0; i--) { // after first line if (i < stack.length - 1) { out += "called\t"; } // each line of stack out += " line " + stack[i].getLineNumber() + "\t" + stack[i].getMethodName() + " (in " + stack[i].getFileName() + ")"; // last line if (i == 0) { out += " <-- error!!"; } out += "\n"; } // print the stack trace System.err.println("My Stack Trace"); System.err.print(out); } // ----------------------------------------------------- // exceptions with Scanner public static void readInExceptions() { Scanner scan = new Scanner(System.in); Bunny b1, b2; System.out.println("Let's make some Bunnys"); System.out.println("I will read string and a number"); System.out.println("pls enter name"); String name = scan.next(); int count; System.out.println("pls enter carrotcount"); try { count = scan.nextInt(); // could cause exception b2 = new Bunny(name, count); System.out.println("you have successfully made a bunny"); System.out.println(b2); } catch (InputMismatchException e) { System.out.println("Can you even type?"); // if scanner fails to nextInt, nextDouble, etc // everything up to the end of the line is still there // in its buffer and this will mess up later input // so tell Scanner to do a nextline to clear it out String leftovers = scan.nextLine(); // Scanner what are you doing? // Scanner go home you're drunk. // System.out.println("scanner was caught eating " + leftovers + " out of the buffer's garbage"); // Scanner STAHP } catch (IllegalArgumentException e) { System.out.println(e); } System.out.println("pls enter name and carrotcount"); System.out.println("I will read two strings and convert to a number"); System.out.println("pls enter name"); name = scan.next(); System.out.println("pls enter carrotcount"); String scount = scan.next(); try { count = Integer.parseInt(scount); // could cause exception b1 = new Bunny(name, count); System.out.println("you have successfully made a bunny"); System.out.println(b1); } catch (NumberFormatException e) { System.out.println("Can you even type?"); } catch (IllegalArgumentException e) { System.out.println(e); } } //------------------------------------------------------ // Demonstrate try-catch to deal with exceptions public static void main(String[] args) { readInExceptions(); // exception may occur, but program continues anyway try { System.out.println(dayOfWeek(0)); System.out.println(dayOfWeek(5)); // this throws exception System.out.println(dayOfWeek(88)); } catch (IllegalArgumentException e) { System.out.println("Error was: " + e); } // exception may occur, but program continues anyway try { // random chance for null pointer OR array OR no exception int ch = (int) (Math.random() * 4); switch (ch) { case 0: badPointer(); break; case 1: badArray(); break; case 2: thrower(); break; default: // only happens if no exceptions System.out.println("Nothing bad happened"); } // if null pointer exception } catch (NullPointerException e) { System.out.println("Null Pointer"); exceptionOutput(e); // if array exception } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array out of bounds!"); exceptionOutput(e); // if BadThing exception } catch (BadThingHappened e) { System.out.println("Apparently something bad happened."); exceptionOutput(e); // no matter what happens } finally { System.out.println("Let's continue, shall we?"); } System.out.println("End of program"); } }