Java coding practices, runtime exceptions, and this scenario

In the following scenario, I try to understand how to handle this code and its relationship with runtimexception As I've read, it's usually better to throw runtime exceptions than relying on static exceptions It may even be better to catch statically checked exceptions and throw unchecked exceptions

Whether there is a case where static exceptions can be caught, which may be catch all exception and only handle exceptions An error message may be logged and continue

In the following code, in the execute1 method and execute2 method, let's say that there is volatile code. Do you catch static exceptions and throw them again? Or there may be other errors:

if(null == someObj){throw new RuntimeException(); }

Is this the method you use?

Pseudo code:

public class SomeWorkerObject {
  private String field1 = "";
  private String field2 = "";

  public setField1() { }
  public setField2() { }

  // Do I throw runtime exception here?
  public execute1() {
    try {
    // Do something with field 1
    // Do something with field 2
    } catch(SomeException) {
      throw new RuntimeException();
    }
  }

  // Do I throw runtime exception here?
  public execute2() {
    try {
    // Do something with field 1
    // Do something with field 2
    } catch(SomeException) {
      throw new RuntimeException();
    }

  }

}

public class TheWeb {

 public void processWebRequest() {

    SomeWorkerObject obj = new SomeWorkerObject();
    obj.setField1("something");
    obj.setField2("something");

    obj.execute1(); 
    obj.execute2();
    // Possibility that runtime exception thrown?

    doSomethingWith(obj);
 }
}

I have a few questions about this code Sometimes I don't want to throw runtimeException because execution stops in the calling method It seems that I caught an error in the method. Maybe I can continue But I will know if I can continue to participate in the program

In the above example, if obj What if execute1 () throws runtimeException and the code exits?

Editor: this guy seems to have answered many of my questions, but I still want to hear your opinion

http://misko.hevery.com/2009/09/16/checked-exceptions-i-love-you-but-you-have-to-go/

"Checked exceptions force me to write meaningless catch blocks: more code, harder to read, and a higher chance that I will mess up re throw logic and eat exceptions."

Solution

When catching an exception and throwing a runtimeException, the reason for setting the original exception to runtimeException is very important Namely

Throw a new runtimeException (originalexception)

Otherwise you won't know what the problem is first

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>