throwing a new Exception is similar with returning a value? :confused:
Printable View
throwing a new Exception is similar with returning a value? :confused:
Yes and no. Throwing a new exception will exit the method like a return, however no value will be returned. Instead, the exception will propagate itself through your code until it is either caught or it hits the top and spits it out for you to read.
i forgot to clarify my question, this is regarding with an if-else structure..
i notice it in an else if/else block.. that when i throw an exception, the compiler didnt asked me to define a return statement..
Throwing interrupts normal program flow. I guess in a sense it does act like a return statement, but like literallyjer said, it's looking for something to catch the exception it threw (well, technically there are other things that can be thrown, but for the most part it'll be exceptions).
Code :public void doIt1(Boolean something) { if (something) { throw new NullPointerException(); } System.out.println("doIt1: this will never get executed"); } public void doIt2() { doIt1(true); System.out.println("doIt2: this well never get executed"); } public void doIt3() { try { doIt2(); System.out.println("doIt3: no exception was thrown"); } catch(NullPointerException e) { System.out.println("doIt3: caught a NullPointer Exception"); } }
i'll keep that one !! \m/ thanks a lot world \m/
Also be vary that throwing exceptions will cost a lot more than just returning a value, so for instance if you have a method which will return either true or false this is better than not returning anything or throwing an exception.
Throwing exceptions takes time.
// Json
The performance difference is almost negligible :P This really only applies when you're throwing a ton of exceptions, then maybe you would want to look into other ways to structure your code.