Sie sind auf Seite 1von 22

1) Which package contains exception handling related classes? java.lang 2) What are the two types of Exceptions?

Checked Exceptions and Unchecked Exceptions. 3) What is the base class of all exceptions? java.lang.Throwable 4) What is the difference between Exception and Error in java? Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow. 5) What is the difference between throw and throws? Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guard against the exceptions. Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. the statement would be as follows: public void doSomething() throws IOException,MyException{} 6) Differentiate between Checked Exceptions and Unchecked Exceptions? Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error. Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. RuntimeException and it's subclasses, Error and it's subclasses fall under unchecked exceptions. 7) What are User defined Exceptions? Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class.

What is the importance of finally block in exception handling? Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc. 9) Can a catch block exist without a try block? No. A catch block should always go with a try block. 10) Can a finally block exist with a try block but without a catch? Yes. The following are the combinations try/catch or try/catch/finally or try/finally. 11) What will happen to the Exception object after exception handling? Exception object will be garbage collected. 12) The subclass exception should precede the base class exception when used within the catch clause. True/False? True. 13) Exceptions can be caught or rethrown to a calling method. True/False? True. 14) The statements following the throw keyword in a program are not executed. True/False? True. 15) How does finally block differ from finalize() method? Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected. 16) What are the constraints imposed by overriding on exception handling?

An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class. 2) ****************************************************************************

1. What will be the output of the program?


public class Foo { public static void main(String[] args) { try { return; } finally { System.out.println( "Finally" ); } } }

A.Finally B. Compilation fails. C. The code runs with no output. D.An exception is thrown at runtime. Answer & Explanation Answer: Option A Explanation: If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances: 1. 2. 3. 4. An exception arising in the finally block itself. The death of the thread. The use of System.exit() Turning off the power to the CPU.

I suppose the last three could be classified as VM shutdown. View Answer Workspace Report Discuss in Forum 2. What will be the output of the program?
try { int x = 0; int y = 5 / x; }

catch (Exception e) { System.out.println("Exception"); } catch (ArithmeticException ae) { System.out.println(" Arithmetic Exception"); } System.out.println("finished");

A.finished C. Compilation fails. Answer & Explanation Answer: Option C Explanation:

B. Exception D.Arithmetic Exception

Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class. If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses). View Answer Workspace Report Discuss in Forum 3. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() { throw new Error(); /* Line 22 */ }

A.ABCD B. Compilation fails. C. C is printed before exiting with an error message. D.BC is printed before exiting with an error message. Answer & Explanation Answer: Option C Explanation: Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error). View Answer Workspace Report Discuss in Forum 4. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (RuntimeException ex) /* Line 10 */ { System.out.print("B"); } catch (Exception ex1) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E"); } public static void badMethod() { throw new RuntimeException(); } }

A.BD C. BDE Answer & Explanation

B. BCD D.BCDE

Answer: Option C Explanation: A Run time exception is thrown and caught in the catch statement on line 10. All the code after the finally statement is run because the exception has been caught. View Answer Workspace Report Discuss in Forum 5. What will be the output of the program?
public class RTExcept { public static void throwit () { System.out.print("throwit "); throw new RuntimeException(); } public static void main(String [] args) { try { System.out.print("hello "); throwit(); } catch (Exception re ) { System.out.print("caught "); } finally { System.out.print("finally "); } System.out.println("after "); } }

A.hello throwit caught B. Compilation fails C. hello throwit RuntimeException caught after D.hello throwit caught finally after Answer & Explanation Answer: Option D Explanation: The main() method properly catches and handles the RuntimeException in the catch block, finally runs (as it always does), and then the code returns to normal. A, B and C are incorrect based on the program logic described above. Remember that properly

handled exceptions do not cause the program to stop executing.

1. What will be the output of the program?


public class Foo { public static void main(String[] args) { try { return; } finally { System.out.println( "Finally" ); } } }

A.Finally B. Compilation fails. C. The code runs with no output. D.An exception is thrown at runtime. Answer & Explanation Answer: Option A Explanation: If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances: 1. 2. 3. 4. An exception arising in the finally block itself. The death of the thread. The use of System.exit() Turning off the power to the CPU.

I suppose the last three could be classified as VM shutdown. View Answer Workspace Report Discuss in Forum 2. What will be the output of the program?
try { int x = 0; int y = 5 / x; } catch (Exception e)

{ System.out.println("Exception"); } catch (ArithmeticException ae) { System.out.println(" Arithmetic Exception"); } System.out.println("finished");

A.finished C. Compilation fails. Answer & Explanation Answer: Option C Explanation:

B. Exception D.Arithmetic Exception

Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class. If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses). View Answer Workspace Report Discuss in Forum 3. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (Exception ex) { System.out.print("B"); } finally { System.out.print("C"); } System.out.print("D"); } public static void badMethod() { throw new Error(); /* Line 22 */ } }

A.ABCD B. Compilation fails. C. C is printed before exiting with an error message. D.BC is printed before exiting with an error message. Answer & Explanation Answer: Option C Explanation: Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error). View Answer Workspace Report Discuss in Forum 4. What will be the output of the program?
public class X { public static void main(String [] args) { try { badMethod(); System.out.print("A"); } catch (RuntimeException ex) /* Line 10 */ { System.out.print("B"); } catch (Exception ex1) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E"); } public static void badMethod() { throw new RuntimeException(); } }

A.BD C. BDE Answer & Explanation

B. BCD D.BCDE

Answer: Option C Explanation: A Run time exception is thrown and caught in the catch statement on line 10. All the code after the finally statement is run because the exception has been caught. View Answer Workspace Report Discuss in Forum 5. What will be the output of the program?
public class RTExcept { public static void throwit () { System.out.print("throwit "); throw new RuntimeException(); } public static void main(String [] args) { try { System.out.print("hello "); throwit(); } catch (Exception re ) { System.out.print("caught "); } finally { System.out.print("finally "); } System.out.println("after "); } }

A.hello throwit caught B. Compilation fails C. hello throwit RuntimeException caught after D.hello throwit caught finally after Answer & Explanation Answer: Option D Explanation: The main() method properly catches and handles the RuntimeException in the catch block, finally runs (as it always does), and then the code returns to normal. A, B and C are incorrect based on the program logic described above. Remember that properly

handled exceptions do not cause the program to stop executing.


1.which package contains exception handling related classes? Ans: java. Lang 2. what are the two types of Exceptions? Ans: Checked Exceptions and Unchecked Exceptions. 3 what is the base class of all exceptions? Ans: java.lang.Throwable 4 what is the difference between Exception and Error in java? Ans: Exception and Error are the subclasses of the Throw able class. Exception class is used for exceptional conditions that user program should catch. Error defines exceptions that are not excepted to be caught by the user program. Example is Stack Overflow. 5 what is the difference between throw and throws? Ans: throw is used to explicitly raise a exception within the program, the statement would be throw new Exception (); throws clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of the method can guardagainst the exceptions. Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma. The statement would be as follows: public void do something () throws IOException, MyException {} 6 Differentiate between Checked Exceptions and Unchecked Exceptions? Ans: Checked Exceptions are those exceptions which should be explicitly handled by the calling method. Unhandled checked exceptions results in compilation error. Unchecked Exceptions are those which occur at runtime and need not be explicitly handled. Runtime Exception and its subclasses, Error and its subclasses fall under unchecked exceptions. 7 what are User defined Exceptions? Ans: Apart from the exceptions already defined in Java package libraries, user can define his own exception classes by extending Exception class. 8 what is the importance of finally block in exception handling? Ans: Finally block will be executed whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally block will be executed. Finally is used to free up resources like database connections, IO handles, etc. 9 Can a catch block exist without a try block? Ans: No. A catch block should always go with a try block. 10 Can a finally block exist with a try block but without a catch?

Ans: Yes. The following are the combinations try/catch or try/catch/finally or try/finally. 11 what will happen to the Exception object after exception handling? Ans: Exception object will be garbage collected. 12 The subclass exception should precede the base class exception when used within the catch clause. True/False? Ans: True. 13 Exceptions can be caught or rethrown to a calling method. True/False? Ans: True. 14 The statements following the throw keyword in a program are not executed. True/False? Ans: True. 15 How does finally block differ from finalize () method? Ans: Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. Finalize () is a protected method in the Object class which is called by the JVM just before an object is garbage collected. 16 what are the constraints imposed by overriding on exception handling? Ans: An overriding method in a subclass May only throw exceptions declared in the parent class or children of the exceptions declared in the parent cla

1) If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B which is a subclass of class A can throw IOException. If the above statement true? Ans: The overriding method can not throw any checked exception other than the exception classes or sub-classes of those classes which are thrown by the overridden method. In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException exception. 2) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of checked exception handling? Ans: Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the application like Network error, File Access Denied etc. Unchecked exceptions are the one which arise because of logic written by the developer. e.g. Trying to access an array element which doesnt exist.

3) If there is common code to be executed in the catch block of 10 exceptions which are thrown from a single try block, then how that common code can be written with minimum effort? Ans: In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code. In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g. catch(SQLException sqle | IOException ioe){} 4) Have you every created custom exceptions? Explain the scenario? Ans: Custom exceptions are useful when the JDK exception classes dont capture the essence of erroneous situation which has come up in the application. A custom exception can be created by extending any subclass of Exception class or by implementing Throwable interface. E.g. A custom exception can be thrown when the custom JSP tag has value for the attribute which is not expected.

5) What is the difference between Validation, Exception and Error? Ans: Validation is the process of making user enter data in a format which the application can handle. Exception handling is the process when the application logic didnt work as expected by the Java compiler. Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory. 6) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?

Ans: finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The kind of code written in a finally block consists of clean up code such as closing of database/file connection. But JDK 7 has come up with try with resources block which automatically handles the closing of resources.

7) What do you understand by Exception chaining? Ans: I have written a blog post for this answer here

8) How will you make the client code to be transparent from business logic exceptions? Ans: The use of Business Delegate design pattern makes the client invisible from business logic exceptions. This helps in decoupling the client from server which helps in better maintainability of the application in terms of future changes in client or business logic code. 9) What are the differences between NoClassDefFoundError and ClassNotFoundException? Ans: NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while executing the program. For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown. ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders. For example: The database driver is not found when trying to load the driver using Class.forName() method.

10) What is the purpose of throw keyword? What happens if we write throw null; statement in a Java program? Ans: throw keyword is used to re-throw an exception which has been caught in a catch block. The syntax is throw e; where e is the reference to the exception being caught. The exception is re-thrown to the client. This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword is used. The use of throw null; statement causes NullPointerException to be thrown. The answers are brief. Do post your comments if you think I have missed anything or discuss any other exception handling question.
******************************************************************************

// : c09:FullConstructors.java // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 // www.BruceEckel.com. See copyright notice in CopyRight.txt. class MyException extends Exception { public MyException() { } public MyException(String msg) { super(msg); } } public class FullConstructors { public static void f() throws MyException { System.out.println("Throwing MyException from f()"); throw new MyException(); } public static void g() throws MyException { System.out.println("Throwing MyException from g()"); throw new MyException("Originated in g()"); }

public static void main(String[] args) { try { f(); } catch (MyException e) { e.printStackTrace(); } try { g(); } catch (MyException e) { e.printStackTrace(); } } } ///:~

Creating Your Own Exception Classes


When you design a package of Java classes that collaborate to provide some useful function to your users, you work hard to ensure that your classes interact well together and that their interfaces are easy to understand and use. You should spend just as much time thinking about and designing the exceptions that your classes throw. Suppose you are writing a linked list class that you're planning to distribute as freeware. Among other methods, your linked list class supports these methods:
objectAt(int n)

Returns the object in the nth position in the list.


firstObject()

Returns the first object in the list.


indexOf(Object o)

Searches the list for the specified Object and returns its position in the list. What Can Go Wrong? Because many programmers will be using your linked list class, you can be assured that many will misuse or abuse your class and its methods. Also, some legitimate calls to your linked list's methods may result in an undefined result. Regardless, in the face of errors, you want your linked list class to be as robust as possible, to do something reasonable about errors, and to communicate errors back to the calling program. However, you can't anticipate how each user of your linked list class will want the object to behave under adversity. So, often the best thing to do when an error occurs is to throw an exception. Each of the methods supported by your linked list might throw an exception under certain conditions, and each method might throw a different type of exception than the others. For example,
objectAt()

will throw a exception if the integer passed into the method is less than 0 or larger than the number of objects currently in the list
firstObject()

will throw a exception if the list contains no objects


indexOf()

will throw a exception if the object passed into the method is not in the list But what type of exception should each method throw? Should it be an exception provided with the Java development environment? Or should you roll your own? Choosing the Exception Type to Throw When faced with choosing the type of exception to throw, you have two choices: 1. Use one written by someone else. For example, the Java development enviroment provides a lot of exception classes that you could use. 2. Write one of your own. You should go to the trouble of writing your own exception classes if you answer "yes" to any of the following questions. Otherwise, you can probably get away with using someone else's:

Do you need an exception type that isn't represented by those in the Java development environment? Would it help your users if they could differentiate your exceptions from those thrown by classes written by other vendors? Does your code throw more than one related exception? If you use someone else's exceptions, will your users have access to those exceptions? A similar question is "Should your package be independent and self-contained?"

Your linked list class can throw multiple exceptions, and it would be convenient to be able to catch all exceptions thrown by the linked list with one handler. Also, if you plan to distribute your linked list in a package, all related code should be packaged together. Thus for the linked list, you should roll your own exception class hierarchy. The following diagram illustrates one possible exception class hierarchy for your linked list:

LinkedListException is the parent class of all the possible exceptions that can be thrown by the linked list class. Users of your linked list class can write a single exception handler to handle all linked list exceptions with a catch statement like this:
catch (LinkedListException) { . . . }

Or, users could write more specialized handlers for each subclass of LinkedListException. Choosing a Superclass The diagram above does not indicate the superclass of the LinkedListException class. As you know, Java exceptions must be Throwable objects (they must be instances of Throwable or a subclass of Throwable). So, your temptation might be to make LinkedListException a subclass of Throwable. However, the java.lang package provides two Throwable subclasses that further divide the type of problems that can occur within a Java program: Errors and Exceptions. Most of the applets and applications that you write will throw objects that are Exceptions. (Errors are reserved for serious hard errors that occur deep in the system.) Theoretically, any Exception subclass could be used as the parent class of LinkedListException. However, a quick perusal of those classes show that they are either too specialized or completely unrelated to LinkedListException to be appropriate. Thus, the parent class of LinkedListException should be Exception. Because runtime exceptions don't have to be specified in the throws clause of a method, many packages developers ask: "Isn't it just easier if I make all of my exception inherit from RuntimeException?" The answer to this question is covered in detail on Runtime Exceptions-The Controversy. The bottom line is that you shouldn't subclass RuntimeException unless your class really is a runtime exception! For most of you, this means "No, your exceptions shouldn't inherit from RuntimeException." Naming Conventions It's good practice to append the word "Exception" to the end of all classes that inherit (directly or indirectly) from the Exception class. Similarly, classes that inherit from the Error class should end with the string "Error". Every application fails once in while. Even the ones built with Java, using design patterns, best practices, and a lot of good intentions. So we better prepare our applications for these situations, right? The first thing an application should do if it fails is to tell as much as possible about the error situation. For example: where exactly in the application did the error occur, what was the Java-method calling sequence, what data was being processed, and so on. In this article I'll present a simple, systematic approach which will help Java developers implement some solid error handling in their code. The building blocks are Java's Exceptionclasses.

The basic stuff about Java Exceptions

I'll not go through all the details of Java's exceptions, there are lot of good books and articles about this. But a short intro might be nice as a starter. Java uses exceptions to report severe errors. If a Java statement fails to execute, the Java VM will create a new instance of an Exception class--or subclass thereof--and then "throw" it. A program can "catch" such an exception, inspect it using its methods, and then try to do something sensible to handle the error. By "severe errors" I refer to situations in a program which the programmer does not consider "normal". This could be a database connection that suddenly drops, an attempt to divide by zero, or anything else that is vital to the proper functioning of a program. What is NOT a severe error is for example when you get end-of-file reading a sequential file. Even if it does not occur frequently it's expected that it will occur, and you should therefore add code in your program to handle this situation. It's a tradition in Java literature to illustrate the use of exceptions by a "division by zero" case, so why change this approach:
public float myDivide(int a, int b) { float r; try { r = a / b; } catch (ArithmeticException e) { System.out.println(e.getMessage()); r = Float.POSITIVE_INFINITY; } return r; }

In this code a divison by zero is caught, and the result is set to Java's value for "infinity". The example is merely to illustrate the technique. It would be simpler--and more correct--to test if "b" had the value zero before making the division. An "ArithmeticException" is a subclass of "RuntimeException", which again is a subclass of class "Exception". All exceptions of class "Exception" or subclasses thereof--except "RuntimeException"s--must be caught. "FileNotFoundException" is not a "RuntimeException", so if you try to read a file with a statement like this
FileInputStream f = new FileInputStream("mydata.txt");

then the Java compiler would ask you to either "try-catch" "FileNotFoundException" or declare it in the throws clause of the method, like this:
public float someMethod() throws FileNotFoundException {...

Using the latter setup the caller of "someMethod" would again need to either catch this exception or to declare it in its own throws clause. If no-one catches an exception it'll end up in the "container" that runs the Java classes. This could be the Java VM, a servlet engine, or something else. The net result would be that the program stops and some error messages are written out, probably a Java-method stack trace containing the error information from the exception class which was thrown. This is indeed useful to the programmer (not to the end-user), but very often not enough to locate the problem. When you catch an error you have some choices:

repair the situation so the program can continue to run normally (as in the example above) throw a new exception which the caller of the failing method then must handle ignore the error (not recommended!) pull the emergency break by calling System.exit()--probably after having written information to log files etc.

A really useful feature is the ability to create your own exception classes. This is done by creating a subclass of class "Exception". If you detect a problem in your application you may now throw one of your own exceptions. By doing this you simplify your error handling code, since you can now handle system errors and application errors in the same, consistent way. So much for the basics.
When things go wrong - collect data!

I'll now describe a general technique, using your own exception classes, that can be used to handle severe, non-repairable errors. This means that your application has detected a situation that can not be neglected, so what's important now is this:
1. 2. 3. 4. collect as much information as possible about what has happened write this data to some persistent media--e.g. a log file or a data base give the user--assuming there is one--some explanatory information about what has happened keep the application alive if this makes sense and you're sure that this will not introduce further damage

The reason for "1" and "2" is obvious: in order for the support people to be able to find out what went wrong, so a program bug can be fixed, and to be able to tell the user what has happened and what the consequences are, you need all the information that you can get. We have all experienced the frustration by receiving error message like "System error at unknown location". If this is all the information the support people get, then it might be impossible to locate the problem. So how do we collect data in a systematic way? Let's consider the general situation where your "top-level" program (which could be a servlet, a JSP-page, or any Java class) calls method "a" in class "A", which again calls method "b" in class "B", where an exception is thrown. Let's for simplicity limit the example to these three levels.

What we should do when the exception in "b" is thrown is this:


1. 2. 3. 4. 5. 6. 7. 8. 9. let "b" catch the exception let the catch-code save all essential data in our own exception class (see the specs below) and... throw this exception let "a" catch it let the catch-code in "a" save its own essential data in a new instance of our own exception class and... throw this exception let the top-level program catch it this program should now ensure that all collected data is written to the proper log files, and give the user at the PC an understandable message of what's going on

class NumberRangeException extends Exception { String msg; NumberRangeException() { msg = new String("Enter a number between 20 and 100"); } } public class My_Exception { public static void main (String args [ ]) { try { int x = 10; if (x < 20 || x >100) throw new NumberRangeException( ); } catch (NumberRangeException e) { System.out.println (e); }

} }

Das könnte Ihnen auch gefallen