Exception – Basics and Tricky questions

Exception in Java

Exception is a class in Java which is a subclass of Throwable class.

Exception can be checked or unchecked.

Checked exceptions are those exceptions which can be detected by compiler, and forces us to handle them. If we can’t handle them then compile time error will come.

Unchecked exceptions are those exceptions which can occur at runtime and compiler will not be having any clue of it. So compile time error will not come even if we don’t handle un checked exception(also called as RunTimeException)

I am going to deal with tricky questions regarding exception.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.kb.exception;
 
public class Exception1 {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            int i=9/0;
            System.out.println(i);
            return;
        } catch (Exception e) {
            System.out.println("exception caught");
            return;
        }
        System.out.println("task completed");
 
    }
 
}
package com.kb.exception;

public class Exception1 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			int i=9/0;
			System.out.println(i);
			return;
		} catch (Exception e) {
			System.out.println("exception caught");
			return;
		}
		System.out.println("task completed");

	}

}

What is the output of the above program, if your ans is as below

exception caught

task completed

then you are wrong, because there is a return in try block so it makes the last line as unreachable code. So compile time error.

If we remove return from try then above output will come.

Ground rule -> if there is a return statement in try then no code after try- catch will be valid.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on