Catching an Exception from a called Method - java

This is something that's been bugging me for a while with regards to Program Flow.
I wanted to know if it's possible to catch an error from a Method in order to stop it from executing the Method that would normally follow it like the example bellow that I can't get to work.
public class MyClass {
public static void main(String[] args) {
// this method catches an exception and stops running
method01();
// this method will continue anyway which I don't want
method02();
};
};
I would normally have a static int variable that will initialize as 0 when the program is run and then if a method ever catches an exception it will increment that int and each method will only run if the int is 0.
This works but I was just wondering if I could replace the int shindig with exception handling.

Can you try:
try {
method01()
} catch (final Exception e) {
// do something
return; ///stop processing exit
}
the method01 will throw Exception:
private void method01() throws Exception {
// something
}

If you only want to terminate the whole program in case of an exception you just need to throw a RuntimeException without any further declaration. There are also specialized sub classes for explicit types of exceptions, like NullPointerException or IllegalStateException. See the "Direct Known Subclasses" section in the JavaDoc.
public class MyClass {
public static void main(String[] args) {
method01();
method02(); //method02 won't be called in case of an exception
}
private static void method01() {
// ...
if (true) // something goes wrong
throw new RuntimeException();
// further code won't be executed in case of an exception
}
private static void method02() {
System.out.println("method02 called");
}
}
Optionally it is possible to handle the exception with a try-catch-block:
public static void main(String[] args) {
try {
method01();
method02(); // method02 won't be called in case of an exception
} catch (Exception e) {
System.err.println("something went wrong");
}
}
// other code keeps unchanged...
If you want to enforce exception handling, you have to throw a subclass of Exception that is not derived from RuntimeException. But those exceptions have to be declared within the method Signature.
private static void method01() throws IOException {
throw new IOException();
}

You put method01 and method02 in to same try block:
public class MyClass {
public static void main(String[] args) {
try {
// This method catches an exception and stops running.
method01();
// This method will not continue if method01 have exception.
method02();
} catch (Exception e) {
e.printStackTrace();
}
}
// declare method01, method02, others...
}
Notice: You have mistakes at the end of code block ( }; }; )

Depends on what your method really does.
If your program should continue working also when an exception arise (e.g. NumberFormatException when parsing an input or in general a checked exception) a lot of people will suggest you to not use exception for flow control, but IMHO in very well defined cases (like NumberFormatException) the flow CAN be controlled by try catch statements and exceptions, it's really up to you.
A way to do so is to use the method returned parameter (also #Nikola answer works in this way, the point is to use the catch part of a try catch as flow control):
public class MyClass {
public static void main(String[] args) {
if(method01()) method02();
};
};
public boolean method01(){
try{
//some business
}catch(MyCheckedException e){
e.printStackTrace();
return false;
}
return true;
}
NB: You should use this approach only in well defined situations! If a file CAN be absent in a directory while opening it (checked FileNotFoundException), you COULD use this approach. If the file SHOULD be there and its not, the exception MUST stop the program.

Related

Java throw keyword

public class MyThrow {
public static void main(String[] args) {
System.out.println(2/0);
throw new ArithmeticException("please be carefull");
}
}
Why is the custom exception not showing?
It is showing the default one.
For Exception handling we would use a try catch statement like
try {
System.out.println(2/0);
}catch(ArithmeticException e) {
System.out.println("Please Be Careful");
}
In your case the Custom Exception is not showing up since in the previous line you have a AthmeticExcpetion hence that exception will be thrown and Java will stop and not execute you exception.

Determining which method throws exception

Below code catches an IOException , the first exception throw will be the one that is caught. To determine which method is throwing the IOException is the sole solution to wrap each method that throws an IOException in a try catch block ? I ask as my planned solution adds alot of try catch code and perhaps there is a cleaner solution to determine which method is throwing IOException ?
import java.io.IOException;
import java.net.SocketException;
public class Driver {
private static void te() throws IOException {
throw new java.net.SocketException("Connection Reset");
}
private static void te2() throws IOException {
throw new java.net.SocketException("Connection Reset 2");
}
private static void te3() throws IOException {
throw new java.net.SocketException("Connection Reset 3");
}
public static void main(String args[]) {
try {
Driver.te();
Driver.te2();
Driver.te3();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The answer depends on your required logic. If the treatment of your exception is supposed to be different depending on which method threw the exception, (meaning that within catch you will need to write different error handling code depending on which method threw the exception, then you do need to wrap each method invocation into separate try-catch. But if the error handling is the same then your code is fine (except that usually, you print your stacktrace into a log file) and you would be able to figure out which method threw the exception by reading your stacktrace as a human user. But then again if the error handling is the same then your code doesn't need to know which specific method threw the exception.
I don't know why you are doing something like that, and surely a real situation would be far away from this code fragment but, in "real life" I would consider extending IOException: so you will have a single try with three catches in the main method. Do you like this solution?
Create a custom exception for each method:
class TeException extends IOException { /* constructor */ }
private static void te() throws TeException {
throw new java.net.SocketException("Connection Reset");
}
Then it is fairly easy to distinguish among multiple exception with separate catch blocks:
try {
Driver.te();
Driver.te2();
Driver.te3();
} catch (TeException e) {
e.printStackTrace();
} catch (Te2Exception e) {
e.printStackTrace();
} catch (Te3Exception e) {
e.printStackTrace();
}
An alternative might be to read the method that failed with the stacktrace:
final String failedMethodName = e.getStackTrace()[0].getMethodName());
You can do it as follows:
try {
Main.te();
Main.te2();
Main.te3();
} catch (Exception e) {
System.out.println(e.getStackTrace()[0].getMethodName());
}
In a real life scenario, you would probably be writing something to a log file in the case of an exception. For example:
public class Driver {
// assuming slf4j
private static Logger logger = LoggerFactory.getLogger(Driver.class);
private static void te() throws IOException {
logger.error("exception happened in te()");
throw new java.net.SocketException("Connection Reset");
}
}
Then, to figure out which methods threw exceptions, you would only need to open the log file and check.

Throwing a parent class exception force to throw its sub class exception event though the sub class exception is caught/handled?

I just got an opportunity to use 3rd party API. It has a parent class exception FooException and it has multiple subclass exceptions.
FooException
|
--- BarException
--- BuzException
--- ZapException
There is a method name run from this library I have to call and this method throws FooException but I decided to let a caller to handle it however I need to catch a specific subclass exception BarException. If it is caught then I have to ignore it then continue with for loop. For all other subclass exceptions are thrown then let a caller must catch/handle them properly.
public void handleGracefully() throws FooException {
for(......) {
try {
3rdPartyAPI.run();
} catch (BarException be) { } // silently ignore
}
}
Based on my limited understanding of Java exception, BarException should be caught in the catch block instead of thrown by its parent exception class FooException. Did I understand it correctly?
You are correct about your understanding of this concept.
By writing this line:
public void handleGracefully() throws FooException {
you are basically saying your compiler "Whenever something tries to call this function, you must expect to catch a FooException". If you are catching a BarException, a BarException will be thrown, not his parent.
Consider the following code:
public class MainClass {
public static void main(String[] args) {
try {
handleGracefully();
} catch (FooException e) {
System.out.println("World is not that cool");
}
}
public static void handleGracefully() throws FooException {
try {
hello();
} catch (BarException be) {
System.out.println("Hello world");
}
}
public static void hello() throws BarException {
throw new BarException("NYAAH");
}
}
Result:
Hello world
Running this MainClass, you'll see that you will never run into World is not that cool. Instead, you'll run into Hello world in your console log. Adding a throw declaration in your BarException handling will trigger the main() logging:
public static void handleGracefully() throws FooException {
try {
hello();
} catch (BarException be) {
System.out.println("Hello world");
throw new FooException("BLEEEEH");
}
}
Result:
Hello world
World is not that cool
POST SCRIPTUM
By all means, if something in this answer is wrong (e.g. something to do with the static value of the methods, or anything making my assumption false), feel free to point it out.

What if a method generates a checked exception and handle it itself?

class Xyz {
public static void yolo() {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e) {
System.out.println("lol");
}
}
public static void main(String args[]) {
Xyz.yolo();
}
}
Since there is no exception that is going out of the yolo method, I don't need to write "yolo() throws IllegalAccessException". Right?
You are correct. You only need to declare unhandled checked exceptions.
Exactly. A method only needs to declare throws for exceptions which leave it and aren't handled by itself.
Perfect!
If you will use throws keyword for handing Exception then this method will not handle the exception rather then main() will handle this exception at time of calling this method.

java exception handling and continuation

I have a Java Program where I get data from a different source. some times while reading I see Exception and the program is exiting.
Mine is in a program that runs every 10minutes.
Public static void main(Strings[] args)
{
...readsource();
}
Private static void readsource() throws IOException
{
...
}
Issue:
I am able to get/See the Exception. But I want the program to continue
To that what is the best logic? I dont see try-catch-finally also is not addressing ..I want the program to continue even after seing the exception (I mean the next iteration should continue). This looks to be a Basic issue not sure how to address this...
Then you need to catch the exception, which you are currently not doing.
try {
readsource();
} catch (IOException e) {
// do something, never catch an exception and not do anything
}
//continue.
Note that exceptions usually indicate something is wrong. Unless you are going to do something about the exception, it might be better to fix the condition causing the exception....
You have to provide an error handler in your method, i.e. surround the call to readsource() with a try-catch block.
public static void main(Strings[] args)
{
try{
...readsource();
}
catch(IOException ioe){
//handle the error here,e.g don't do anything or simply log it
}
}
If you don't rethrow the exception in the catch block, execution will fall off the end of the catch block and continue as if there was no exception.
If you mean you'd like to recall the method wether an Exception was thrown or not just place this in a while loop i.e:
Public static void main(Strings[] args)
{
boolean run=true;
while(run) {
try {
System.out.print("Hello,");
readsource();
throw new IOException();
if(1==2)run=false;//stop the loop for whatever condition
} catch(IOException ioe) {
ioe.printStackTrace();
}
System.out.println(" world!");
}
}
}
Private static void readsource() throws IOException
{
...
}

Categories

Resources