0

I have written following sample class to experiment with exception. I have two identical methods, one throws RuntimeException whereas one with Exception not compiling.

Sample code

public class Test{

    public static void main(String... args){
        System.out.println(3%-2);
        System.out.println(4%-2);

        Test t1 = new Test();
        t1.mtd1(101);
        t1.mtd2(101);

    }

    public int mtd1( int i) throws RuntimeException{
        System.out.println("mtd");

        return i;
    }

    public int mtd2( int i) throws Exception{
        System.out.println("mtd");

        return i;
    }


}

Error

C:\Java\B-A>javac Test.java
Test.java:10: error: unreported exception Exception; must be caught or declared to be thrown
                t1.mtd2(101);
                       ^
1 error
user6
  • 33
  • 5
  • When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.So use try-catch to handle. – Mihir Apr 18 '16 at 05:01

2 Answers2

1

You have two options. You can either catch the exception inside your main() method, or you can have main() also throw an exception.

Option One:

public static void main(String... args){
    System.out.println(3%-2);
    System.out.println(4%-2);

    Test t1 = new Test();
    try {
        t1.mtd1(101);
        t1.mtd2(101);
    }
    catch (Exception e) {
        // do something
    }
}

Option Two:

public static void main(String... args) throws Exception {
    System.out.println(3%-2);
    System.out.println(4%-2);

    Test t1 = new Test();
    t1.mtd1(101);
    t1.mtd2(101);
}

By the way, it is a bit strange to see you catching RuntimeException since this exception is unchecked. Normally unchecked exceptions represent things going run at runtime in such a way that is generally not possible to handle them.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

All the exception which derives from the class RuntimeException are referred to as unchecked exceptions. And all the other exceptions are checked exceptions. A checked exception must be caught somewhere in your code. If not code will not compile.

Raghu K Nair
  • 3,854
  • 1
  • 28
  • 45