Java Exception Interview Questions
Java Exceptions is a large topic and lot of topics are need to be covered. Here i will give you some introduction about Exceptions in Java.
What is Exception in Java?
An Exception is a programming error. Exceptions are of two types. Checked Exceptions and Unchecked Exceptions. An Error is not an Exception.
- What is an Exception in Java? : Exception is a programming error in Java.Exceptions are inherited from Throwable,exception,Runtime. Exceptions are handled by try and catch statements.
- Difference between Checked and Unchecked Exception in Java: Checked Exceptions are handled by try and catch. They occur at Compile time.ex:- IOException Unchecked Exceptions are those programming errors. ex:- Nullpointer exception.
- Is it necessary to follow try with catch block: No it's not necessary to have a catch block after try. you can also use finally after try block.
- What is the difference between throw and throws in Java:
1)throw is used to explicitly throw an exception. throws is used to declare an exception. | |
2)checked exceptions can not be propagated with throw only. checked exception can be propagated with throws. | |
3)throw is followed by an instance. throws is followed by class. | |
4)throw is used within the method. throws is used with the method signature. | |
5)You cannot throw multiple exception You can declare multiple exception e.g. public void method()throws IOException,SQLException. |
6. How to write Custom Exception in Java: A Custom Exception is an User Defined Exception. It should inherit the Exception base class.
package com.sis.crm.exception.util;
public class AlreadyExistException extends Exception{
@Override
public String getMessage() {
return super.getMessage();
}
public AlreadyExistException(String message, Throwable exception) {
super((exception != null && (message == null || message.length() == 0)) ? exception.getMessage() : message, exception);
}
@Override
public String toString() {
return super.toString();
}
}
7. What is the difference between Final,Finalize, and Finally keyword in Java: Final keyword is used for creating immutable class in java. Finalize keyword is used for Garbage Collection in Java. Finally keyword is used to execute some code that is to close some resources etc. example if an error occurs in try block and error occurs in catch block, and finally is used to close some database connection etc.
No comments:
Post a Comment