Link to home
Start Free TrialLog in
Avatar of mcgettiu
mcgettiu

asked on

Static methods

If I have two static methods
method1 - throws an exception
method2 - does not

If method2 calls method1 - how can this compile?
If appears to be compiling with no problems

I thought the calling method would have to have include a try..catch to cover this?
Avatar of kiranhk
kiranhk

u must be having a the Exception declared in the throws clause of method2 if you are not having a try/catch block.

if a method throws a subclass of java.lang.RuntimeException, then you don't need to specify it in the declaration.
Example:  NullPointerException is a subclass of RuntimeException, so you don't need to declare that method2 throws it.


class Test {
 
  static void method1() throws NullPointerException {
    throw new NullPointerException();
  }
 
  static void method2() throws NullPointerException {
    method1();
  }
 
  public static void main(String[] args) {
    method2();
  }
   
}
ASKER CERTIFIED SOLUTION
Avatar of GrandSchtroumpf
GrandSchtroumpf

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi mcgettiu,

>> If appears to be compiling with no problems
If the exception is not a RuntimeException, if the 2 methods are in differents classes, and method1 wasn't throwing any exception when you compiled method2, then try to recompile both classes (delete the .class files to be sure it's recompiled).

thanks for accepting :)