throwing a new Exception is similar with returning a value?![]()
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
throwing a new Exception is similar with returning a value?![]()
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.
chronoz13 (October 23rd, 2009)
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).
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"); } }
chronoz13 (October 23rd, 2009)
i'll keep that one !!thanks a lot world
![]()
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 negligibleThis 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.