Quick Refresh : Java : Exception Handling

Java : Exception Handling

Q1) What is an Exception?

Ans) The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result. An exceptional event is a occurrence of condition which alters the normal program flow. Exception handler is the code that does something about the exception.

Q2) Exceptions are defined in which java package?

Ans)All the exceptions are subclasses of java.lang.Exception

Q3) How are the exceptions handled in java?

Ans)When an exception occurs the execution of the program is transferred 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 a guarded region.
The catch clause matches a specific exception to a block of code which handles that exception.
And the clean up code which needs to be executed no matter the exception occurs or not is put inside the finally block.

Q4) Explain the exception hierarchy in java.

Ans) All exception and errors types are sub classes of class Throwable, which is base class of hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError, OutOfMemory are example of error. Two types of Exceptions: Checked exceptions and UncheckedExceptions. Both type of exceptions extends Exception class.Exception


Q5) What is Runtime Exception or unchecked exception?

Ans) Runtime exceptions represent problems that are the result of a programming problem. Such problems include arithmetic exceptions, such as dividing by zero; null pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions need not be explicitly caught in try catch block as it can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can). The solution to rectify is to correct the programming logic where the exception has occurred or provide a check. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.

Q6) What is checked exception?

Ans) Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch block. Compiler check if we have handled these exception or not. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword. These exceptions are sub class of Exception. Example: IOException, InterruptedException.

Q7) What is difference between Error and Exception?

Ans) An error is an irrecoverable condition occurring at run-time. Such as OutOfMemory error. These JVM errors and you can not repair them at run-time. Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

Q8) What is difference between ClassNotFoundException and NoClassDefFoundError?

Ans) A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.
Consider if NoClassDefFoundError occurs which is something like java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.

Q) How JVM handle an Exception? 

Default Exception Handling : 

Whenever inside a method, if an exception has occurred, the method creates an Object known as Exception Object and hands it off to the run-time system(JVM). The exception object contains name and description of the exception, and current state of the program where exception has occurred. Creating the Exception Object and handling it to the run-time system is called throwing an Exception.There might be the list of the methods that had been called to get to the method where exception was occurred. This ordered list of the methods is called Call Stack.Now the following procedure will happen.

- The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler.
- The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods were called.
- If it finds appropriate handler then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
- If run-time system searches all the methods on call stack and couldn’t have found the appropriate handler then run-time system handover the Exception Object to default exception handler , which is part of run-time system. This handler prints the exception information in the following format and terminates program abnormally.
Exception in thread "xxx" Name of Exception : Description
... ...... .. // Call Stack

Q9) What is throw keyword?

Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of Throwable.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}


public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException("Throwing exception using throw keyword");
}
}

Q10) What is use of throws keyword?

Ans) If the function is not capable of handling the exception then it can ask the calling method to handle it by simply putting the throws clause at the function declaration.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}


public void child throws MyCustomException{
//put some logic so that the exception occurs.
}

Q11) What are the possible combination to write try, catch finally block?

Ans)
1) 
try{
//lines of code that may throw an exception
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}finally{
//the clean code which is executed always no matter the exception occurs or not.
}

2) 
try{
}
finally{} 

3)

 try{
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}

The catch blocks must always follow the try block. If there are more than one catch blocks they all must follow each other without any block in between. The finally block must follow the catch block if one is present or if the catch block is absent the finally block must follow the try block.

Note: - For each try block there can be zero or more catch blocks, but only one finally block.

- The finally block is optional.It always gets executed whether an exception occurred in try block or not . If exception occurs, then it will be executed after try and catch blocks. And if exception does not occur then it will be executed after the try block. The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection.

Q12) How to create custom Exception? 

Ans) To create your own exception extend the Exception class or any of its subclasses.
e.g.
1 class New1Exception extends Exception { } // this will create Checked Exception
2 class NewException extends IOExcpetion { } // this will create Checked exception
3 class NewException extends NullPonterExcpetion { } // this will create UnChecked exception

Q13) When to make a custom checked Exception or custom unchecked Exception?

Ans) If an application can reasonably be expected to recover from an exception, make it a checked exception. If an application cannot do anything to recover from the exception, make it an unchecked exception.

Q14)What is StackOverflowError?

Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM.
e.g. void swap(){
swap();
}

Q15) Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope?

Ans) Any Exception that can be thrown by a method is part of the method's public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.

Comments

Popular posts from this blog

Ashtavinayak Temples | 8 Ganpati Temples of Maharashtra | Details Travel Reviews

Ramoji Film City, Hyderabad, India

Pune to Ganpatipule Trip