// APS101, Winter 2009: Lecture 35 (Apr. 6) // // Review: last time we finished our discussion of basic sorting algorithms - make sure you know these for the final exam! // Today we will cover the basics of Exception Handling. // exception = an error in Java. // For example: int[] x; x[0] // NullPointerException x = new int[2]; x[5] // ArrayIndexOutOfBoundsException // these exceptions don't just appear magically - they are "thrown" somewhere! // Throwing an Exception throw new Exception(); throw new Exception("This message describes the problem."); // these exceptions can also be "caught" using a try-catch block: try { // execute some code that might throw an exception } catch (Exception e) { // if an exception is thrown, catch it and respond to it } // Example: 6 / 0 // ArithmeticException try { int x = 6 / 0; } catch (Exception e) { System.out.println("Cannot divide by zero!"); } x // doesn't exist! // let's try that again... int x; int y = 6; int z = 10; try { x = y / 0; } catch (Exception e) { x = z; } x // = 10! // now, let's use exception handling to make the Tic-Tac-Toe game more robust (error-free) // what if the user enters a row and/or column that is too high? i.e. greater than 2. // right now, the program crashes due to an ArrayIndexOutOfBoundsException // how do we handle this? (use a try-catch block to catch the exception!) // we can also write a customized exception, throw it when the input is invalid, and // catch it in the driver class. // (see TTTException.java) TTTException e = new TTTException(); // an exception is an object! e e.getMessage() TTTException e = new TTTException("APS101 Exception"); e.getMessage() // (see method setMark in TicTacToe.java for the changes we made) // a TTTException is thrown in 3 different cases - what are they? // (see TTTDriver.java for the changes we made) // we added a try-catch block to handle any TTTException that is thrown by method setMark // Also note that you can catch multiple exceptions in the try-catch block: try { // try some piece of code } catch (Exception1 e) { // respond to Exception1 } catch (Exception2 e) { // respond to Exception2 } ...