Hello friends! Today I attend an interview for a Java developer position(Fresher). The Interview person ask me a question: What is Checked Exception & Un-checked Exception. I replied 'Exceptions that are checked during the compilation time itself are called Checked exception, If they shouldn't, compiler will throw Compile time error. e.g) FileNotFoundException, SQLException, etc..'.
I thought it would be the correct answer, but the interviewer again asks me why the compiler throws the error, how the compiler knows the exception will arise, because the Exception arise at Runtime.
I said, Sorry sir, i don't know. Then he replied with the correct answer. He said 'If you create an object for a class which
"throws any Exception during the Constructor invocation" or "If you call a method from that class which throws any Exception"
you need to catch them or again you put the "throws" statement in your constructor or method. In this way you need to catch them before runtime. Hence they are called Checked Exception.
At starting, I didn't know the answer, but he taught me with an actual reason.
I know this is a simple topic but i forgot to cover this in preparation.
Don't you forget guys.
class CheckedExceptionParent{
// this class throws an Exception at constructor invocation.
public CheckedExceptionParent() throws Exception{
throw new Exception("Exception from parent.");
}
}
public class CheckedExceptionsDemo {
public static void main(String[] args) {
CheckedExceptionParent demo = new CheckedExceptionParent(); // this line throws compile time error.
//hence we must enclose this with try-catch or else declare throws statement.
}
}
Top comments (0)