350 likes | 362 Views
Learn how to handle and catch exceptions in Java to prevent program crashes. Understand the difference between checked and unchecked exceptions.
E N D
Exceptions • Exceptions are objects that store information about the occurrence of an unusual or error condition. • They are thrown when that error or unusual condition occurs. • You have seen these before • OutOfBoundsException, NullPointerException, ArithmeticException, etc. • Until now, any exception that occurred always resulted in a program crash. • This doesn’t have to happen!
Exceptions • Java can handle exceptions keep your program from crashing. • This is known as catching an exception. • If any exception occurs and is not caught, the program will crash. • You can do 2 things with Exceptions: • catch – Do something about the problem (hopefully fix it) • throw – pass the buck (hope some one else fixes it)
Exceptions • There are two types of exceptions in Java, unchecked exceptions and checked exceptions
Unchecked Exceptions • Unchecked exceptions are any class of exception that extends the RuntimeException class at some point in its inheritance hierarchy • This includes the most common exceptions. • ArithmeticException, NullPointerException, OutOfBoundsException • Unchecked exceptions occur all over a program and can be very numerous
Unchecked Exceptions • The cost of checking them can be greater than the benefit of handling them • Thus, Java compilers do not require that you declare or catch unchecked exceptions in your program • They can be handled if the programmer deems it necessary
Checked Exceptions • Checked exceptions are exceptions that do not extend the RuntimeException class • Checked exceptions must be handled to avoid a compile-time error • An example of a checked exception is the IOException that may occur when the readLine method is called on a BufferedReader object
Checked Exceptions • There are two ways to handle checked exceptions • You may declare the exception using a throws clause or you may catch the exception • To declare an exception, you add the keyword throws followed by the class name of the checked exception to the method header public void method1() throws IOException{ … // stuff here }
Checked Exceptions • Any method that calls a method that throws a checked exception must also handle the checked exception by either catching to throwing it • If an exception is always handled using the throws clause, it will eventually propagate all the way back to the main method • If the main method throws the exception (and the exception occurs while the program is running) then the program will crash.
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); }
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } main calls method1
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } main calls method1 method1 calls method2
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } main calls method1 method1 calls method2
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } main calls method1 method1 calls method2 method2 can cause an IOException
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } main calls method1 method1 calls method2 If it does, it will throw it to whoever called it
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } main calls method1 method1 calls method2 If it does, it will throw it to whoever called it
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } main calls method1 If method1 causes and exception, it will throw it as well
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } Now main gets the Exception
Checked Exceptions public static void main(String[] args) throws IOException{ method1(); } public static void method1() throws IOException{ method2(); } public static void method2() throws IOException{ stdin.readLine(); } Since it throws it, the program will crash
Checked Exceptions • A method that calls a method that throws a checked exception must also handle the exception by catching or throwing it • If an exception is always handled using the throws clause, it will eventually propagate all the way back to the main method • If the main method throws the exception (and the exception occurs while the program is running) then the program will crash.
Checked Exceptions • An alternative to simply passing the buck, is to catch the exception • A method that catches and Exceptoin will do something to correct the error or recover and continue the program's execution, if the exception occurs • To catch an exception, you must first indicate what code may cause the exception. • This is called a try block and is a part of a try-catch statement.
Checked Exceptions • The try block surrounds the statement and any related statements that may cause the exception to occurs • The catch block follows the try block and defines the code that should be executed if the exception occurs • If more than one type of checked exception needs to be caught, write a separate catch clause for each type.
Checked Exceptions public void method2(){ try{ String s = stdin.readLine( ); System.out.println(s); } catch (IOException ex){ System.out.println(“IOException” + ex + “occurred”); }
Checked Exceptions • All Exceptions that DO NOT extend the RuntimeException class are checked exceptions. • The compiler requires a throws clause or a try-catch statement for any method that may cause a checked exception • If a checked exception occurs and is not caught before it reaches the main method of the application, the program will crash.
Exceptions • How do we know if it is checked or unchecked? • Compiler will tell you • Check the java API!!!
Exceptions • Questions??
Other Exceptions int x; // Get a valid integer from the user try { System.out.print( "Enter an integer: " ); x = Integer.parseInt( stdin.readLine() ); } catch ( NumberFormatException e ) { // A NumberFormatException occurred System.out.println( e.getMessage() + " is not a valid format for an integer." ); }
Other Exceptions boolean valid = false; int x; // Get a valid integer from the user while ( ! valid ) { try { System.out.print( "Enter an integer: " ); x = Integer.parseInt( stdin.readLine() ); valid = true; // only executes if the string // entered does not cause an Exception } catch ( NumberFormatException e ) { // A NumberFormatException occurred System.out.println( e.getMessage() + " is not a valid format for an integer." ); } } // repeats until a valid integer has been entered
Multiple Exceptions try { FileReader fileReader = new FileReader( “file.txt” ); BufferedReader inFile = new BufferedReader( fileReader ); String temp = inFile.readLine(); while ( inFile.ready() ) { System.out.println(inFile.readLine(); } fileReader.close(); } catch ( FileNotFoundException e ) { System.out.println( e.getMessage() + " FILE NOT FOUND" ); } catch ( IOException e ) { System.out.println( e + " EXCEPTION" ); }
Exceptions • Questions??
Exceptions • After the try-catch statement, you may optionally include a finally clause • A finally clause is used to perform operations that must happen whether or not an exception occurs in the try block • If a finally clause is used, it must follow all catch clauses for a given try block • There can only be one finally clause for a given try block.
Exceptions try { ... } catch ( IOException e ) { ... } catch ( Exception e ) { ... } finally { // any statements that you always want to occur }
Exceptions • You may declare the exception using a throws clause or you may catch the exception • Any method that calls a method that throws a checked exception must also handle the checked exception by either catching to throwing it • Whatever is in a finally block is always executed at the end of a try-catch block
Exceptions • Exceptions are a good way to separate the code that handles errors or very special cases from the code that is most commonly executed. • This can help you focus on the intended purpose of the code without having to write many nested control statements to verify information at each step of execution.
Exceptions • Questions??