Sequential throw declarations in my Java code - java

'Hi, everyone! I have a question about exception handling in Java. What is launched firstly if there is sequential "throw" declarations and why? Below is an example of a method like that:
public void myMethod(boolean ok) {
if (ok) {
// do something...
} else {
throw new myRuntimeException();
throw new RuntimeException ();
}
}
Thanks in advance!

Most compiler would flag the second "throw" as error : "Unreachable code" - as it will never get executed.
It would be like writing code after a return (except a finally block) - it is never going to get executed - hence illegal.

Once you throw, the flow of execution is interrupted and the following happens:
if you are inside a try block, it goes to to the corresponding catch
if not, the Throwable (Exception in your case) is passed up the call chain, leaving myMethod() and going to the method that called it
this process is repeated until you either reach a try block or the top of the call stack, in which case your program will terminate.
Thus, only your first exception is thrown, the throw new RuntimeException (); statement is never reached.

Related

Java: Is There Any Way to Specify When an Exception Will be Thrown?

I have code something like this pseudo code:
void doSomething(int data) throws Exception{
if(data < 10) throw new Exception("Exception thrown"); // throws an exception based on a condition
else { ... } // logic goes here
}
When I try to call doSomething in the main function, it give me an error:
public static void main(){
doSomething(11); // Error! unreported exception
}
Here is a link to the previous example.
So I have to do one of the following:
Add a try catch block around every doSomething call
Add a throws statement in main
Get rid of the throws statement in doSomething
Make the condition a precondition, so that not following it results in undefined behavior or something similar.
3 will not work, because doSomething may throw an exception when a client is using it.
1 and 2 are simply redundant, and I think they should be avoided.
Finally, 4 is the most appealing to me (being primarily a C++ coder) but runs contrary to Java programming.
My question is: What is the best way out of the mentioned options (or any other options), and what is the best way to implement it?
It really depends on the context You are working with.
If You want the code to stop executing at the moment the Exception is thrown, You could use Runtime exceptions, You don't have to catch them.
The good use case would be a REST endpoint. If something goes wrong during the computation of the response, we could throw ResponseStatusException - the Runtime exception which would immedeately return the Http Response Error to the client and stop any further execution of the code.
In contrary, if You have a logic which has to be executed even if the exception was thrown, the best way would be to use try - catch blocks, or to add throws statement to the method declaration and try - catch in parent method.

Why is return statement not required here?

If I have the method:
public static boolean getA() throws Exception{
try{
throw new Exception();
}finally
{
}
}
There is no return statement required. Moreover, if we try to add a return statement at the end, it produces the "unreachable statement" error.
Why is this so? Is it certain the the program will not come out of the block, and that the exception will be thrown?
Furthermore, if we add a catch block instead of the finally block, then it requires the return statement to be present there.
Because you have specified an throw statement and there is nothing else in the method definition. That is why. I guess it was that simple.
The return statement will be unreachable, because it is going to throw the exception irrespective of everything.
The catch will require the return statement, because you are handling the exception explicitly now it wants you to return as you have declared in the method definition.
I hope you are aware, you can keep both catch and finally blocks. Because they serve different purpose of their own.
Java Exceptions.
Yes it is certain that the program will throw an exception, this is the first line of what you're doing in your try block.
Even if it wasn't the first statement in your try block, you don't have a catch block so any other theoretically previously thrown exception would not be caught.
It might be because when you throw an exeception, execution stops, hence why finally will never run. When you catch the exception, execution will proceed, and you will have to return.

Exception handling in this scenario

Trying my hands on Java for the first time, please be kind. I have following code in a Web Controller where a service is called based on enclosed Switch-Case statement.
Issue I am facing is, if the service call throws an Exception, this exception gets shown on the JSP page. Basically the code never reaches the lines:
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
How do I make sure the executing goes to above lines, even though an exception is thrown in the WebService call at:
statusFlag = myWebService.getMeStatus();
Should I enclose the whole Switch Statement inside try-catch block?
Snippet:
#Controller
public String mySpringController() throws Exception
{
//rest of the controller code
switch ( condition )
{
case MAY :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
case JUNE :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
case JULY :
statusFlag = myWebService.getMeStatus();
if(!statusFlag)
{
model.addAttribute("statusFlag", statusFlag);
return "myJspPage"
}
break;
default:
//Do something by default.
}
return "myJspPage";
}
If that line is throwing an Exception it means that it is never returning, so statusFlag is still with its original value and the execution of that method has stopped. You need to surround it in a try - catch if you want to catch the Exception and do something about it.
I see you are using Spring. In Spring Controllers you can also have your own special methods which get invoked when an Exception occurs. Using the #ExceptionHandler annotation.
I don't see the purpose of your switch statement since each case does the same thing.
But basically you can put your webservice call in a try-catch block
try{
webservice.call();
}
catch (Exception e){
// handle the exception
}
finally{
//anything in here will be executed regardless if an exception is caught or not
}
You're writing Java in the style of C++, where you're returning error codes and then checking them to determine whether anything went wrong. There are a number of issues with this snippet, but the reason for the exception display is that you never catch the exception that's being thrown. Where you should put your try-catch block depends on what the exception means; if it's something that isn't specific to a particular month, then yes, enclose the entire switch statement to share the error handling.
As an aside, did you copy and paste your actual code, or did you try to retype an example? Those case blocks all look identical.

unreported exception handling in java

I am a Java beginner and knows that try...catch statements are used to handle exceptions; means when an exception is thrown by try block, catch block is executed. So,my question is when I tried the following code (without try catch) it throws a unreported IOException in read() method but when I use try catch it works fine.
Why doesn't the control get transferred to catch statement when the above mentioned exception occurs in the try block and exception occured is printed?
here is my code:
class Test00 {
public static void main(String args[]) {
char ch;
try {
ch=(char)System.in.read();//here exception is thrown without using try..catch
System.out.println(ch);
} catch(Exception e) {
System.out.print("exception occured");
}
}
}
I think the compiler is saying to throw an exception,that's why the code worked with try catch.But why not the catch block is executed?is i am getting something wrong.
The compiler is telling you that the exception could be thrown, and that you have to cater for that possibility.
The compiler is doing a static analysis of your code. It can't tell how the code will actually run in practise.
This can be frustrating. e.g. if I write:
new URL("http://www.stackoverflow.com");
the compiler will insist that I catch a MalformedURLException. It's clear that URL is fine, but the compiler warns me since I could construct a URL object using:
new URL(potentiallyDubiousUserInput);
and I can't guarantee what that string potentiallyDubiousUserInput is going to be.
These are known as checked exceptions and you have to handle them (either catch or declare them to be thrown further). They can be a pain, and you'll see in languages such as Scala that all exceptions are unchecked. That is, you don't explicitly have to handle them.
See this question/answer for more info.
You have to distinguish (and tell us clearly, so that we don't have to puzzle it out) between what the compiler is telling you and what happens at runtime.
In your case, without the try-catch the compiler was telling you that the read() might throw, and that you would have to deal with the exception somehow. That's what you did by adding the try-catch.
However, when you then ran the program, it didn't actually throw (and generally speaking, it's very unlikely that this program will throw), so it never entered the catch block.
This is because System.in.read() can throw IOException which is a checked Exception. And as mentioned in JLS 11.2.3 about checked exception:
It is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the method or constructor.

Unable to understand behaviour of Finally Block

I am new to Java language and cannot understand the behavior of finally block in this program. This program should exit after printing BC whereas it is printing BCD. Please help.
class Main
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C");
}
System.out.print("D");
}
public static void badMethod() throws Exception
{
throw new Exception(); /* Line 22 */
}
}
You're catching the exception (in the catch block) and not rethrowing it - so you're effectively handling the exception, and execution then proceeds as if it weren't thrown. The program only exits because it reaches the end of the main method - it's not like it's terminated abruptly.
If you change your code to either rethrow the exception from the catch block or just don't catch it in the first place (both of which will require you to declare that main throws Exception, of course) then it won't print D.
There is nothing to cause the program to exit.
The whole point of a catch block is to catch the exception and prevent it from propagating further.
After catching an exception, execution continues.
The finally block doesn't finalize the program, it just ensure to execute every time the try catch block runs whereas there is an exception or not..
It would print BC if you re-throw the exception in catch block.
catch (Exception ex)
{
System.out.print("B");
throw ex;
}
Then you'll have to declare your main as
public static void main(String [] args) throws Exception
Finally is called at the end of a try/catch block. It gets called even if the try fails and the catch is executed. The Finallyblock itself is only not executed if the program is killed somehow (JVM dies, forced to close, etc.)
In your example D is executing because it is outside of the try/catch/finally{} blocks.
There is a nice blog post on catching exceptions and the try/catch/finally behaviour here.
Which is correct. The above code will.
Try to execute badMethod and will fail
Execute the code in catch
Execute the code in finally
Continue in execution - print out the D
The finally block is processed after the try or catch block runs (depending on whether an exception was thrown/caught or not). If the exceptions were all caught properly and handles by the catch, it will run finally and then continue running the rest of the method.
Finally is the must executable block of java program.
It allows all the allocated resources of the currently running program to get free and make it available for the other applications if required.
This is mainly used when we share the common resources like Database or the devices.
Think of the finally block as an independent block of code(s) you'll still expect your method to continue executing irrespective of whether an exception occurs or not.
And so in your case, badMethod throws an exception which is consequently caught by the catch block, your main then continue by executing the finally block independently.
In other words, if badMethod decides not to throw an exception, your finally block would still continue execute before reaching the end of the method.
Therefore with finally been an independent block it is then possible to also do something like this in your main code if prefered.
try
{
fooA();
}
finally
{
fooB();
}
Your program is functioning in the following way:
1. Call a bad method that throws an exception
2. Catch the exception
3. Execute the finally block
4. Resume
In Java, when an exception gets thrown it does not necessarily end program execution if the exception is handled. Your program does not actually handle the exception but catches it anyway and this is enough for the JVM to think it's ok to resume execution.
The output BCD is quite the right output.

Categories