Checked exception | SoloLearn: Learn to code for FREE!

+1

Checked exception

Why in the following code we are getting a compile time error "java unreachable statement" https://code.sololearn.com/c3F5E97TiWUm/?ref=app

6/28/2018 3:11:47 AM

harshit

6 Answers

New Answer

+3

Because the throw statement stops the main program running so everything after it can't be reached and generates an error.

+3

harshit as nonzyro stated your if statement in the second program allows a path to reach the later statements. In the first program, it can't bypass the throw so it can never execute the statement.

+1

Then why this code is running with only arun time exception-error and no " java unreachable statement" error? https://code.sololearn.com/cHOXuEwc6jhl/?ref=app

+1

John Wells can I get your Facebook handle.. I need a coach, and I hope you'd be my coach Wells: Ebere Chidi Ellis I do not give out my personal information. Either join Discord or comment on my code. Please delete this spam. https://www.sololearn.com/Discuss/830853

+1

0

harshit in the first example in your OP, you're throwing unconditionally (there's no specified "throw this because that" ---> if (condition) throw new ErrConst; ). In the second code you posted, it's conditional ("throw this if insufficient funds"). I'm not a Java expert, but throw is generally supposed to be used to handle extreme runtime errors, not trivial cases. We try never to exit a program on a bad status, even with bad user input or faulty libraries. In fact C++ programmers are expected to handle all kinds of errors with try...catch and even if (methods/functions should always return error status, eg: if (func_call()) {...} ). But I digress. Your error, I believe, is the unconditional throw (always throw).