Checked exception | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

28th Jun 2018, 3:11 AM
harshit
harshit - avatar
6 Answers
+ 3
Because the throw statement stops the main program running so everything after it can't be reached and generates an error.
28th Jun 2018, 3:55 AM
John Wells
John Wells - avatar
+ 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.
28th Jun 2018, 12:02 PM
John Wells
John Wells - avatar
+ 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
28th Jun 2018, 4:41 AM
harshit
harshit - avatar
+ 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
28th Jun 2018, 8:29 AM
Ebere Chidi Ellis
Ebere Chidi Ellis - avatar
+ 1
ok thanks
28th Jun 2018, 12:08 PM
Ebere Chidi Ellis
Ebere Chidi Ellis - avatar
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).
28th Jun 2018, 10:30 AM
non