Exception Handling

Looking to get certified as a Java SE 11 Developer with Oracle?

Check out this highly rated Udemy course by the Skilltoz team with excellent practice questions that will help you prepare for the Java Certification exam.

For sample Questions, you can also refer to http://talks.skilltoz.com/java-11-certification-exam-questions/

To learn in detail about exception handling, you can refer these Oracle Java tutorial pages. In the below sections, you can learn some tips from this topic to prepare for the certification exam.

Checked and Unchecked Exceptions

All exceptions in Java are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. Checked exceptions have to be handled ie; declared in throws clause or handled using a try/catch block. However, unchecked exceptions do not need to be handled. Here is a quiz question that will help you brush up this concept.

Quiz

Q. Which of the following are true about the below code?

public class Q21 {
	public static void main(String[] args) {
		Q21 myClass = new Q21();
		myClass.myMethod();
	}
	public void myMethod() {
		anotherMethod();
	}
	public void anotherMethod() {
		throw new Exception();
	}
}

A. The code compiles fine
B. The code will compile fine only if anotherMethod() declares Exception in throws clause
C. The code will compile fine only if anotherMethod() and myMethod() declare Exception in throws clause
D. The code will compile fine only if anotherMethod(), myMethod() and main() methods declare Exception in throws clause

Checked exceptions need to be handled by declaring in the throws clause or using the try/catch block. So this code will not compile.

For this to compile, the method anotherMethod() that throws this exception must declare it in the throws clause.
As the method is being called from myMethod(), it must also declare it in its throws clause. Applying the same logic, main method should also declare it in its throws clause.

To learn more, refer https://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

Leave a Reply

Your email address will not be published. Required fields are marked *