Java / Exception
1. How are the exceptions handled in java?
When an exception occurs, the execution of the program is aborted and handed over to an appropriate exception handler. The try-catch-finally block is used to handle the exception. The code in which the exception may occur is enclosed in a try block ,also called as guarded region . The catch claus...
2. Difference between Error and Exception in Java.
An error is an irrecoverable condition occurring at runtime, for example, OutOfMemory error. These JVM errors can not be fixed at runtime. Though an error can be caught in catch block, the execution of application will halt as errors are not recoverable. An Exception could be handled by using eit...
3. What are checked and unchecked exceptions?
In Java, there are two types of exceptions. Checked exceptions : Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples ? SQL...
4. How do we handle more Than One Type of Exception using catch block in Java?
Using multiple catch blocks we may specify multiples exception to be handled in Java. For example, the below code handles both IOException and SQLException. catch (IOException ioEx) { logger.log(ioEx); throw ioEx; catch (SQLException sqlEx) { logger.log(sqlEx); throw sqlEx; } Although the above c...
5. What happens if an exception is thrown from the finally or catch block in Java?
The new exception thrown at a catch or finally block will propagate out of that block, resulting the current exception be aborted or ignored as the new exception is propagated outward. The new exception starts unwinding up the stack as ususal just like any other exceptions, stepping out of the cu...
6. Will the finally block be executed when the catch clause throws exception in Java?
Yes. Finally clause is executed even when an exception is thrown from anywhere in either try or catch block. See the below example. package net.javapedia.exceptions; import java.io.IOException; public class FinallyException { public static void main(String[] args) throws IOException { try { Syste...
7. What is a user defined/custom exception in Java?
User-defined exceptions can be implemented by, defining a class to respond to an exception and embedding a throw statement in the try clause where the exception can occur or declaring that the method to throw the exception to invoking method where it is handled. A new exception can be defined by ...
8. How to create unchecked exception in Java?
If the custom exception needs to be unchecked, then have the user defined exception class extend RuntimeException. public class UserDefinedException extends RuntimeException { UserDefinedException(String msg) { super (msg); } }
9. What will happen to the Exception object after exception handling in Java?
The Exception object will be garbage collected in the next garbage collection process.
10. How does finally block differ from finalize() method in Java?
A finally block will be executed whether or not an exception is thrown and is used to release those resources held by the application. Finalize is a protected method of the Object class, which is called by the Java Virtual Machine (JVM) just before an object is garbage collected.
11. Does a finally block always run in Java?
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. System.exit cause the finally block to not execute. 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 wh...
12. Does return statement allow finally block to execute in Java?
Yes. The return statement executes the finally block. public class FinallyReturn { public static void main (String [] args) { System.out.println( "Value returned = " + myMethod()); } public static int myMethod () { try { return 0 ; } finally { return 1 ; } } } Output: Value returned = 1
13. Should a catch block always follow try block in Java for Exception handling?
The try block needs to be followed by either catch or finally block or both. Any exception thrown from a try block needs to be either caught in the catch block or else any specific tasks to be performed are placed in the finally block. The exceptions that are likely to be thrown should be declare...
14. Explain finally block in Java.
Java finally block is used to execute important code such as closing connection, stream and files. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block.
15. What is an Exception in Java?
Exception is an abnormal condition which occurs during the execution of a program and disrupts normal flow of the program. This exception must be handled properly. If it is not handled, program will be terminated abruptly.
16. In Java 7, can we catch by grouping exceptions that are hierarchically related?
We can group only un-related exceptions together. It is illegal to group exceptions which has parent-child relationship. For example, it is illegal to write a multi-catch statement like this: try { ... } catch ( FileNotFoundException | IOException ex ) { System.err.println("File not found.") ; } ...
17. What is try-with-resources statement in Java?
The try-with-resources statement is a try statement that declares one or more resources, where resources are objects that must be closed and try-with-resources statement ensures that each resource is closed at the end of the statement. This statement is introduced in Java 7.
18. Can we have multiple resources inside a try-with-resources in Java?
Yes. We can use multiple resources inside a try-with-resources block and have them all automatically closed.
19. What is the order the resources are closed using try-with-resources?
The resources will be closed in reverse order of the order in which they are created / listed inside the parentheses in try statement.
20. Advantages of using try-with-resources in Java.
Minimize lines of code, Automatic resource management, No need of finally block just to close the resources, Manage multiple resources.
21. What happens when the AutoCloseable resource is null in Java Try-With-Resource?
A resource is closed only if it is initialized to a non-null value. If the reference is null, no attempt is made to call close() on it, no NullPointerException is thrown, and it works as expected.
22. Difference between Error and runtime exceptions in Java.
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...
23. Difference between throw and throws clause in Java.
The throw clause explicitly throw as an exception while throws clause intimate the compiler that exceptions are being handled and this method might throw. The throws need to be used in the methods definition and also while invoking the method that raises checked exceptions.
24. Can try block exist without any catch and finally block in Java?
No, The try block must be followed by either catch or finally block and only try block results in compile time error.
25. Will the resources be closed at finally/catch in try with resources?
In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
26. Order of closing resources in try with resources Java statement.
In case of multiple resources, the close methods of resources are called in the opposite order of their creation.
27. What is exception chaining in Java?
Exception chaining is the technique of handling exceptions by re-throwing a caught exception after wrapping it inside a new exception. This is very helpful in wrapping unchecked exceptions into a checked exception. The entire trace of errors is captured in the stacktrace of the exception. The bel...
28. What is stack trace?
A stack trace provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred. A stack trace is a useful debugging tool that you'll normally take advantage of when an exception has been th...
29. What is the order of catch blocks when catching more than one exception?
When you are handling multiple catch blocks, make sure that you are specifing exception sub classes first, then followed by exception super classes. Otherwise we will get compile time error.
30. What are the improvements on Try-With-Resources in Java9?
In Java7, try-with-resources syntax needed a fresh variable to be declared for each resource being managed by the statement. Java9 has improved this statement by eliminating the need of new variable to be created. FileOutputStream fileOutputStream = new FileOutputStream("/file.txt"); try(FileOutp...
31. Can we have an empty catch block?
We can have an empty catch block but its a bad practice. Never have an empty catch block as if the exception is caught by that block, we will have no information about the exception and it wil be difficult to debug it. There should be at least a logging statement to log the exception details in ...
32. Can we use FileNotFoundException and IOException in Java multi catch?
No . You will get compile time exception, "The exception FileNotFoundException is already caught by the alternative IOException". This is because FileNotFoundException is a subclass of IOException. To fix it, use single catch statements for these exceptions.
33. Important methods of Java Exception Class.
Exception and all its subclasses doesnt provide any specific methods and all of the methods are defined in the base class Throwable. String getMessage() This method returns the message String of Throwable and the message can be provided while creating the exception through its constructor. S...
34. When do you subclass an exception?
If the exception type is not represented by existing Exception in the Java platform, or if you need to provide more information to client code to treat it in a more precise manner, then you should create a custom exception. Deciding whether a custom exception should be checked or unchecked depend...
35. Can you catch OutOfMemoryError?
Yes, it can be handled as the same way as exception. However it is not a good idea to handle it.
36. Can you catch java.lang.Error?
Yes. However, it should not be caught as it is a bad practice.
37. Give few examples of checked exceptions.
The checked exceptions are ClassNotFoundException, SQLException, IOException and FileNotFoundException.
38. Give few examples of unchecked exceptions.
The unchecked exception include NullPointerException, ArrayIndexOutOfBoundsException, NumberFormatException and RuntimeException.
39. What is OutOfMemoryError in java?
OutOfMemoryError is a sub class of java.lang.Error which occurs when JVM runs out of memory.
40. What is StackOverflowError in java?
StackOverflowError is a subclass of java.lang.Error which is thrown by the JVM when stack overflows.
41. Explain exception handling when overriding a method?
Overriding method cannot throw higher Exception than the overridden method. If the original method throws IOException then the overriding method cannot throw superclass of IOException, I.e., Exception but it can throw any subclass of IOException or does not throw any Exception at all. This rule o...
42. Can overridden method throw RuntimeException when original method throw ArithmeticException?
Yes, in case of unchecked exception, overridden method can throw.
43. Can we keep other statements in between try, catch and finally blocks?
No, we cannot. They form a single unit. try { // Statements that may raise exceptions } // No statement allowed here catch(Exception ex) { //Catching the exceptions here } // No statement allowed here finally { // This block is always executed }
44. Can I write only try block without any catch and finally block?
No, It results compilation error. The try block must be followed by either catch or finally block.
45. Explain Throwable class.
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or its subclass) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be ...
46. Difference between final, finally and finalize in Java.
final keyword is used to make a variable or a method or a class as "unchangeable". Final variable : A variable which is declared as final, its value cannot be changed once it is initialized. class FinalKeywordExample { public static void main (String [] args) { final int x = 10 ; x = 200 ; // Com...
47. What is rethrowing an exception?
Exceptions that raised in the try block are handled in the catch block. If it is unable to handle that exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception. try { String s = null ; System.out.println(s.equals( hello )); //This statement throws N...
48. Explain the rules of Exception Handling in terms of Method Overriding?
Broadly there are 2 rules. If superclass method has not declared any exception using throws clause then subclass overridden method cannot declare any checked exception though it can declare unchecked exception. If superclass method has declared an exception using throws clause then subclass overr...
49. Types of OutOfMemoryError in Java.
Exception in thread thread_name: java.lang.OutOfMemoryError: Java heap space . java.lang.OutOfMemoryError: GC Overhead limit exceeded . java.lang.OutOfMemoryError: Requested array size exceeds VM limit . java.lang.OutOfMemoryError: Metaspace. java.lang.OutOfMemoryError: request size bytes for rea...
50. Name some of the tools for probing Java Memory Leaks?
JProbe, JHat and OptimizeIt.
51. Which exception advised not to be thrown from close method when implementing AutoCloseable?
It is strongly advised to not have the close method throw InterruptedException . This exception interacts with a thread's interrupted status, and runtime misbehavior is likely to occur if an InterruptedException is suppressed. More generally, if it would cause problems for an exception to be supp...
52. Which is the child interface of Autocloseable?
Closeable interface.
53. What does close method throw: Closeable vs AutoCloseable?
Closeable extends AutoCloseable and both are interfaces. Closeable throws IOException and AutoCloseable throws Exception.
54. How do I rethrow an exception with custom message without losing stack trace?
Exceptions are immutable and its message cannot be altered after they've been created. Try the below code snippet. throw new Exception("Custom exception: " + messageId, originalException);