Ans.
Q2. Difference between checked exceptions and unchecked exceptions?
Ans. There are 3 kinds of exceptions:
1. The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. Ex. FileNotFoundException
2. The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. Ex: Suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction.
3. These are exceptional conditions that are internal to the application. These usually indicate programming bugs, such as logic errors or improper use of an API. The cost of checking for the runtime exception often outweighs the benefit of catching it. Ex: Null PointerException is a RunTime Exception.
Consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.
Q3. What is an Error in java and how is it different from Exception?
Ans.
1. Exceptions are those which can be handled at the run time with try-catch-finally blocks where as errors cannot be handled.
Ex: Array out of bonds, attempt to divide by zero etc.
2. You can anticipate RunTime Exceptions but not errors. Error may be due to I/O, logical error, etc. This causes your program to halt and you can't continue after that.
Errors are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
Q4. What is exception specification and do we need to specify RunTimeException in that?
Ans. Telling what type of exceptions a method can throw is exception specification.
ex: method throws type1, type2, type3
You need not specify RunTimeException in exception specification. RuntimeException (or anything inherited from it) is a special case, since the compiler doesn’t require an exception specification for these types. The output is reported to System.err.
If a RuntimeException gets all the way out to main() without being caught, printStackTrace() is called for that exception as the program exits.
Keep in mind that only exceptions of type RuntimeException (and subclasses) can be ignored in your coding, since the compiler carefully enforces the handling of all checked exceptions. The reasoning is that a RuntimeException represents a programming error.
Q5. Can you declare to throw an exception but still not throw it?
Q6. Can I use throws Error or throws Throwable clause. If yes, what are the advantages of same?
Ans. Yes, I can use throws Error and throws Throwable clause. However, there is no use/advantage of same. One should try to catch exceptions as specific as possible.
You should catch errors, only if you can handle them. Normally errors are due to I/O errors or external to application, thus they should be allowed to go to main program and shouldn't be caught. Similarly saying throws Throwable will force to catch all kinds of exceptions and errors.
Q7. Exception Restriction
Ans.When you override a method, you can throw only the exceptions that have been specified in the base-class version of the method. Although exception specifications are enforced by the compiler during inheritance, the exception specifications are not part of the type of a method, which comprises only the method name and argument types. Therefore, you cannot overload methods based on exception specifications. In addition, just because an exception specification exists in a base-class version of a method doesn’t mean that it must exist in the derived-class version of the method. This is quite different from inheritance rules, where a method in the base class must also exist in the derived class. Put another way, the "exception specification interface" for a particular method may narrow during inheritance and overriding, but it may not widen—this is precisely the opposite of the rule for the class interface during inheritance.
Points:
1. Interface CANNOT add exceptions to existing methods from the base class. i.e if a method is defined in a class and an interface, another class is extending and implementing, method signature will be taken from class and not interface.
2. Overridden methods can throw inherited exceptions. Thus, when you put the reference in derived class object itself, handle inherited Exception. However, if put the object reference in base class object; you should catch base class Exception as per the exception specification in base class method.
3. The restriction on exceptions does not apply to constructors. Derived class constructor can throw anything it wants, regardless of what the base-class constructor throws. However, since a base-class constructor must always be called one way or another, the derived-class constructor must declare any base-class constructor exceptions in its exception specification.
4. A derived-class constructor cannot catch exceptions thrown by its base-class constructor.
Q8. Exception arguments
Ans. There are two constructors in all standard exceptions: The first is the default constructor, and the second takes a string argument (i.e a message) so that you can place pertinent information in the exception:
throw new NullPointerException("t = null");
Ex: In a normal case if we have a statement like 'return i*i', since this is a complex statement involving an expression hence the expression would first be evaluated and once evaluation is complete then the value would replace the placeholder originally occupied by the expression. For example: if i = 10, then 'return i*i' would become 'return 100' and now this statement doesn't have any reference to 'i' to have any other value change in future. The pending control transfer statement would always be in a ready-to-run shape and it would not have any reference to any variable and hence any change to 'i' in the finally block would not affect the value associated with the pending 'return' statement.
Q10. Can a catch block have multiple arguments.
Q11. Describe guarded region and exception handler.
Ans. This is catch block.Q4. What is exception specification and do we need to specify RunTimeException in that?
Ans. Telling what type of exceptions a method can throw is exception specification.
ex: method throws type1, type2, type3
You need not specify RunTimeException in exception specification. RuntimeException (or anything inherited from it) is a special case, since the compiler doesn’t require an exception specification for these types. The output is reported to System.err.
If a RuntimeException gets all the way out to main() without being caught, printStackTrace() is called for that exception as the program exits.
Keep in mind that only exceptions of type RuntimeException (and subclasses) can be ignored in your coding, since the compiler carefully enforces the handling of all checked exceptions. The reasoning is that a RuntimeException represents a programming error.
Q5. Can you declare to throw an exception but still not throw it?
Ans. You can claim to throw an exception that you really don’t. The compiler takes your word for it, and forces the users of your method to treat it as if it really does throw that exception. This has the beneficial effect of being a placeholder for that exception, so you can actually start throwing the exception later without requiring changes to existing code. It’s also important for creating abstract base classes and interfaces whose derived classes or implementations may need to throw exceptions.
Ans. Yes, I can use throws Error and throws Throwable clause. However, there is no use/advantage of same. One should try to catch exceptions as specific as possible.
You should catch errors, only if you can handle them. Normally errors are due to I/O errors or external to application, thus they should be allowed to go to main program and shouldn't be caught. Similarly saying throws Throwable will force to catch all kinds of exceptions and errors.
Q7. Exception Restriction
Ans.When you override a method, you can throw only the exceptions that have been specified in the base-class version of the method. Although exception specifications are enforced by the compiler during inheritance, the exception specifications are not part of the type of a method, which comprises only the method name and argument types. Therefore, you cannot overload methods based on exception specifications. In addition, just because an exception specification exists in a base-class version of a method doesn’t mean that it must exist in the derived-class version of the method. This is quite different from inheritance rules, where a method in the base class must also exist in the derived class. Put another way, the "exception specification interface" for a particular method may narrow during inheritance and overriding, but it may not widen—this is precisely the opposite of the rule for the class interface during inheritance.
Points:
1. Interface CANNOT add exceptions to existing methods from the base class. i.e if a method is defined in a class and an interface, another class is extending and implementing, method signature will be taken from class and not interface.
2. Overridden methods can throw inherited exceptions. Thus, when you put the reference in derived class object itself, handle inherited Exception. However, if put the object reference in base class object; you should catch base class Exception as per the exception specification in base class method.
3. The restriction on exceptions does not apply to constructors. Derived class constructor can throw anything it wants, regardless of what the base-class constructor throws. However, since a base-class constructor must always be called one way or another, the derived-class constructor must declare any base-class constructor exceptions in its exception specification.
4. A derived-class constructor cannot catch exceptions thrown by its base-class constructor.
Q8. Exception arguments
Ans. There are two constructors in all standard exceptions: The first is the default constructor, and the second takes a string argument (i.e a message) so that you can place pertinent information in the exception:
throw new NullPointerException("t = null");
Q9. Talk about try-catch-finally block.
Ans. try-block would of course be started first and executed till any exception or a control transfer statement is encountered. If it's an exception, the control would go to catch and subsequently to finally to complete the execution. If it's a control transfer (like a return, break, continue, etc.), then the control transfer statement is evaluated and kept in a pending state. Once the finally is executed, then the runtime sees if finally-block has any valid control transfer statement or not and if found then the pending control transfer statement is forgotten and the one present in finally is actually executed. In case finally-block doesn't have any control transfer statement then the pending one i.e. from try or catch block whichever is latest, is executed and mind you it's not re-evaluated.
Ex: In a normal case if we have a statement like 'return i*i', since this is a complex statement involving an expression hence the expression would first be evaluated and once evaluation is complete then the value would replace the placeholder originally occupied by the expression. For example: if i = 10, then 'return i*i' would become 'return 100' and now this statement doesn't have any reference to 'i' to have any other value change in future. The pending control transfer statement would always be in a ready-to-run shape and it would not have any reference to any variable and hence any change to 'i' in the finally block would not affect the value associated with the pending 'return' statement.
Q10. Can a catch block have multiple arguments.
Ans. No. Each catch clause (exception handler) is like a little method that takes one and only one argument of a particular type. Though we can have multiple catch blocks for multiple exceptions.
Ans. Guarded region is a section of code that might produce exceptions and is followed by the code to handle those exceptions. Exception handler, in other words, is catch block.
Q12. Exception Handler block.
Q12. Exception Handler block.
catch( Type1 id1) {
.......
}
catch (Type2 id2) { ........
}
The identifier (id1, id2, and so on) can be used inside the handler, just like a method argument. Sometimes you never use the identifier because the type of the exception gives you enough information to deal with the exception, but the identifier must still be there.
Q13. Is it possible to not execute the finally block?
Ans. If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. The only time finally won't be called is if you call System.exit() or if the JVM crashes first.
Q14. Exception Chaining
Ans. Often you want to catch one exception and throw another, but still keep the information about the originating exception — this is called exception chaining
Prior to JDK 1.4, programmers had to write their own code to preserve the original exception information. Only Throwable subclasses that provide the cause argument in the constructor are the three fundamental exception classes:
Error (used by the JVM to report system errors), Exception, and RuntimeException.If you want to chain any other exception types, you do it through the initCause() method rather than the constructor.
// Using initcause to set an exception as causeDynamicFieldsException dfe = new DynamicFieldsException();
dfe.initCause(new NullPointerException());
throw dfe;
// using constructor to set an exception as causecatch(NoSuchFieldException e) {
throw new RuntimeException(e);
// This was not possible before JDK 1.4, as that is user defined exception.
}
However, now all Throwable subclasses have the option to take a cause object in their constructor. The cause is intended to be the originating exception, and by passing it in you maintain the stack trace back to its origin, even though you’re creating and throwing a new exception
Q15. StackTrace. ie. printStackTrace()
Ans. Information provided by printStackTrace( ) can also be accessed directly using getStackTrace( ). This method returns an array of stack trace elements, each representing one stack frame. Element zero is the top of the stack, and is the last method invocation in the sequence (the point this Throwable was created and thrown). The last element of the array and the bottom of the stack is the first method invocation in the sequence.Ans. If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. The only time finally won't be called is if you call System.exit() or if the JVM crashes first.
Q14. Exception Chaining
Ans. Often you want to catch one exception and throw another, but still keep the information about the originating exception — this is called exception chaining
Prior to JDK 1.4, programmers had to write their own code to preserve the original exception information. Only Throwable subclasses that provide the cause argument in the constructor are the three fundamental exception classes:
Error (used by the JVM to report system errors), Exception, and RuntimeException.If you want to chain any other exception types, you do it through the initCause() method rather than the constructor.
// Using initcause to set an exception as causeDynamicFieldsException dfe = new DynamicFieldsException();
dfe.initCause(new NullPointerException());
throw dfe;
// using constructor to set an exception as causecatch(NoSuchFieldException e) {
throw new RuntimeException(e);
// This was not possible before JDK 1.4, as that is user defined exception.
}
However, now all Throwable subclasses have the option to take a cause object in their constructor. The cause is intended to be the originating exception, and by passing it in you maintain the stack trace back to its origin, even though you’re creating and throwing a new exception
Q15. StackTrace. ie. printStackTrace()
for(StackTraceElement ste : e.getStackTrace())
System.out.println(ste.getMethodName());
Q16. Describe default printStackTrace behaviour.
Ans. By default, the information is sent to System.err. Default version is e.printStackTrace();and others are:
void printStackTrace(PrintStream)
void printStackTrace(java.io.PrintWriter)
Ex:
MyException: Originated in g()
MyException: Originated in g()
at FullConstructors.g(FullConstructors.java:15)
at FullConstructors.main(FullConstructors.java:24)
where MyException -> Exception Name
Originated in g() -> Message while exception was created
Originated in g() -> Message while exception was created
And rest is stacktrace.
Ans. The line where fillInStackTrace( ) is called becomes the new point of origin of the exception.
If you simply rethrow the current exception, the information that you print about that exception in printStackTrace( ) will pertain to the exception’s origin, not the place where you rethrow it. If you want to install new stack trace information, you can do so by calling fillInStackTrace( ), which returns a Throwable object that it creates by stuffing the current stack information into the old exception object. Here’s what it looks like:
throw (Exception)e.fillInStackTrace();
Q18. How can I find caller method/object of a calling method?
Ans.
1. Using getStackTrace on current thread (since Java 1.5) –
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
2. Calling getStackTrace on a Throwable instance (since Java 1.4) - Creating an instance of Throwable and then calling getStackTrace()method on it.
2. Calling getStackTrace on a Throwable instance (since Java 1.4) - Creating an instance of Throwable and then calling getStackTrace()method on it.
StackTraceElement[] ste = new Throwable().getStackTrace();
3. Using native method (like getCallerClass method) of some JVM implementation specific classes. We should avoid such a practice as we may otherwise sacrifice the portability of the code.
3. Using native method (like getCallerClass method) of some JVM implementation specific classes. We should avoid such a practice as we may otherwise sacrifice the portability of the code.
Potential Problem with #1 and #2: In certain situations, few JVM implementations may either omit one or more stack frames from the stack trace or they might not have any stack frame info at all related to this Throwable instance as a JVM implementation is allowed to return a zero-length array by Java language specs.
Another possible issue is that compile-time inlining may show skewed results. Say if a method A internally calls another method B and B calls C. Let's suppose the method B has no other executable statement. Obviously this will be a good candidate for compile time inlining as the compiler might replace the call to method B inside method A definition with a call to method C. In such cases, the above two approaches will return the caller method of method C as method A and not as method B what the source code might suggest. Please note that this will require you to turn on the optimization of the compiler. Results may vary across compilers as different compilers may have different criteria for inlining - some might never do.
No comments:
Post a Comment