Unformatted text preview:

Java Exceptions: In a glance ❏ Like almost everything else in Java, exception is an object. ❏ It is thrown by JVM when run-time error occurs. ❏ You can catch an exception to prevent program from terminating. Purpose 1.Coping with unexpected errors ❏ The real world is far from perfect. ❏ You want the user to enter a number, but s/he has to enter a string. ❏ The file that your program wants to open does not exist ❏ a light ray from outer space changed the circuitry of a computer. In code try { file = new FileInputStream("topsecretfile.dat"); in = f.read(); } catch(FileNotFoundExcetion e1){ System.out.println(e1+"ALERT:SECRET MAY BE REVEALED"); } catch(IOException e2){ file.close(); } Let’s walk through this block of code 1) First, java execute the statements in the try block. If any method call declares that it throws an exception, you put it in a try block, which is basically saying you are not 100% confident that it will work normally, you can only “try”. 2) If the FileInputStream (a constructor) cannot find the file, it will throw an FileNotFoundException. Java will then skip everything else in the try block, and find the first catch block that matches the exception it throws. Because FileNotFoundException is an subclass of IOException, it matches both catch block in this case. When this is the case, it goes to the first one found. 3)If the file stream is created successful, but the read() method throws an exception, then the second catch clause is matched. In this block, we just close the file.4)If both method call run without error, no catch clause is matched, and the program will continue. 2.Escaping a sinking ship Sometimes, you want to throw your own exceptions. Here is a case Suppose you are writing a compiler on your own, and you need to go throw a file with many nested loops. Deep in the program stack, your compiler reached the end of file. If may be caused by someone accidentally deleted the last 100 lines of the file. What do you do now? Do you want to spend all the time back trace the program or just tell that careless person: hey, be careful next time. The second option is much less painful and simply requires your program to throw an exception. You will first have create a class that extends Exception. There are no other things needed in this class. Its only purpose is to distinguish this exception from others. public class UnexpectedEndOfFileException extends Exception{ } Then, in your compiler class method, you would have public void readLine () throws UnexpectedEndOfFileException{ //some code if (something is wrong){ throw new UnexpectedEndOfFileException(); } //more code } *Note that the method signature “throws UnexpectedEndOfFileException” is required. You can also declare a method that throw more than one exceptions. for example, public void readFile() throws UnexpectedEndOfFileException, NoCommaException{ //some code readLine(); //more code }Then, when you do public void Compile(){ try{ readFile(); } catch(UnexpectedEndOfFileException e1){} catch(NoCommaException e2){} } The UnexpectedEndOfFileException and NoCommaException will be caught in Compile(). If an exception propagate all the way out of main, JVM prints the error message and halts. The hierarchy Below is a simple Java OOP Hierarchy of Throwable Objects Checked and Unchecked Exceptions Unlike exception, an error is usually something fatal and unrecoverable, like running out of memory out stack overflow. Even though you can catch anything throwable objects, catching an error is usually inappropriate. Throwable has two types, unchecked and checked. Uncheck simply means a method can throw it without declare a throw clause.For example public void foo(int arg){ if (arg is wrong){ throw new IllegalArugmentException("Your input is so wrong!!!") } }All errors and RunTimeExceptions(and their subclasses) are unchecked. In the code above, IllegalArugmentException is a subclass of RunTimeException. All other exceptions are checked. If your method throw one without catching it, it must declare the possibility of it in a “throws“ clause. For example, public void bar () throws IOException{ if (user input something wrong){ throw new IOException("wrong input, how could you?"); } } When a method calls another method that throw a checked exception, it has two choices. 1) catch it 2) declare so that it also “throws” that exception *The best way to figure out what exception to declare is to declare none and let the compiler error tells you. Related Question: Each of the exceptions XException, YException, ZException, BException, CException, DException, and EException is declared so it “extends Exception”. Which exception, if any, propagates out of the following code? . public static void z() throws Exception { try { throw new XException(); } catch (YException y) { throw new ZException(); } catch (Throwable t) { try { throw new BException(); } catch (RunTimeException c) { throw new CException(); } throw new DException(); } catch (BException b) { throw new EException(); } }Answer:BException ====================================================== ***Notes taking from Professor Jonathan Shewchuk CS61B Class and HKN chapter @Berkeley


View Full Document

Berkeley COMPSCI 61B - Java Exceptions

Documents in this Course
Lab

Lab

4 pages

Matrix

Matrix

3 pages

Numbers

Numbers

14 pages

Lectures

Lectures

12 pages

Project 1

Project 1

24 pages

Exam

Exam

8 pages

Load more
Download Java Exceptions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Java Exceptions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java Exceptions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?