Java Generic Exception - java

I am dealing with JaudioTagger API to manipulate MP3 files, I have to repeat the following exceptions over and over again... I was thinking of having a generic exception handler where I could forward each exception maybe with a flag number and the generic method would be deal with it by having different switch cases maybe ? Is it possible ? I would really appreciate if someone could give the method signature or a way to call it
} catch (CannotReadException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (ReadOnlyFileException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAudioFrameException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (TagException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}

Pre-JDK 7 all you can do is write a utility function and call it from each of the catch blocks:
private void handle(Exception ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
private void someOtherMethod() {
try {
// something that might throw
} catch (CannotReadException ex) {
handle(ex);
} catch (ReadOnlyFileException ex) {
handle(ex);
} catch (IOException ex) {
handle(ex);
} catch (InvalidAudioFrameException ex) {
handle(ex);
} catch (TagException ex) {
handle(ex);
}
}
Starting in JDK 7, you can use multi-catch:
private void someOtherMethod() {
try {
// something that might throw
} catch (CannotReadException | ReadOnlyFileException | IOException
| InvalidAudioFrameException | TagException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
See "Catching multiple exceptions".

This answer is obsolete starting with Java 7. Use multi-catch like John Watts shows in his answer.
I suggest using
try {
/* ... your code here ... */
} catch (Exception ex) {
handle(ex);
}
And handle it this way: (you have to replace the OtherException that you don't handle or remove the throws)
private static void handle(Exception ex) throws SomeOtherException {
if (ex instanceof CannotReadException || ex instanceof ReadOnlyFileException) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} else if (ex instanceof SomeOtherException) {
throw (SomeOtherException) ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new RuntimeException(ex);
}
}

Related

narrower catch and broader catch inside of it in Java

I have a following nested try - catch in Java as you see below.
One of my concern is that
First ( and third ) catch is InterruptedException ( and Throwable ) and we have general Exception in this catch block.
I'm wondering this exception structure makes sense or not ( ie.
narrower outside catch, and broader inside catch ).
Catch blocks don't throw an exception, it's just logging.
if this structure
is not good, is there a better way?
public void run() {
try {
} catch (InterruptedException ex) { // narrower
....
try {
...
} catch (Exception e) { // broader
...
} finally {
...
}
} catch (ShutdownSignalException shutdownException) {
try {
} catch (InterruptedException ignored) {
}
} catch (Throwable ex) {
try {
} catch (Exception e) {
}
try {
} catch (Exception e) {
} finally {
}
}}}

How to handel JsonMappingException try catch [duplicate]

This question already has answers here:
Unable to catch JsonMappingException
(7 answers)
Closed 8 years ago.
I am new to jackson, i have written this code and my ide says at catch block .
I dont understand this . I have included jar.
incompatible types
required:java.lang.Throwable
found :org.codehaus.jackson.map.JsonMappingException
This is the method
private void jacksonTest() {
try {
org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), someObj);
} catch (IOException ex) {
Logger.getLogger(GR_XX.class.getName()).log(Level.SEVERE, null, ex);
} catch (JsonMappingException ex) {
// incompatible types
// required:java.lang.Throwable
// found :org.codehaus.jackson.map.JsonMappingException
} catch (Exception ex) {
Logger.getLogger(GR_XX.class.getName()).log(Level.SEVERE, null, ex);
} catch (Throwable ex) {
Logger.getLogger(GR_XX.class.getName()).log(Level.SEVERE, null, ex);
}
}
As you can see in the documentation of JsonMappingException, it is a subclass of IOException. This means your first catch would already handle the JsonMappingException. If you want to handle it seperately, you'll have to catch it before IOException.
In case of Multiple catch Exception Hierarchy comes into action
Try something like this :
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), someObj.class);
}
catch (JsonMappingException ex) { }
catch (IOException ex) {}
catch (Exception ex) {}
catch (Throwable ex) {}
I got answer from stackoverflow.com/a/14920842/2194456
I had the same issue. It seems the class inherited by the JsonMappingException class is not in the JAR file. I just reverted to version 1.9 which didn't have the problem.

Java JUnit - Is it possible to determine if & which exception is thrown? [duplicate]

This question already has answers here:
How to do unit test for Exceptions?
(5 answers)
Closed 8 years ago.
I've got a method in a normal class that has a try with multiple catches:
Object returnObject = null;
try {
// do some stuff to set returnObject
}
catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
return returnObject;
In my UnitTest I would like to test if the method successfully went through the stuff in the try, without going into one of the caught Exceptions.
I know that if I didn't had a try-catch in my normal class' method, I could just use a try-catch with Assert.fail(...);, or an ExpectedException-tag in front of the test-method.
BUT, my method does have a try-catch, and I want to UnitTest if I successfully go through the try, without going to one of the catches. (As you can see in the code above, all my catches only have a ex.printStackTrace();)
PS: I also can't use the stuff in the try to test. So I can't check if returnObject is null after the method, because in this case I want it to be null (but without going to a catch). Otherwise I wouldn't asking this question.
Thanks in advance for the responses.
I think your Unit test doesn't have to know has exception been thrown and catched within method or not. Your unit test should test contract of your method. And it shouldn't concern about how this contract is implemented. So if contract of the method is return null if something bad happened and it's OK then test it in this way. If invoker should know was exception or not while method was executing and type of exception, then you may return some wrapper-object with method hasException();
You can assign exception name in a global String variable (use global - as you already returning an object), and compare the string in assert statement. If no exception case, returned string would be blank.
public static String message=""; // global variable
Object returnObject = null;
try {
// do some stuff to set returnObject
}
catch (NoSuchMethodException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (InstantiationException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (IllegalArgumentException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
return returnObject;
And assert -
assertEquals(ClassName.message.equalsIgnoreCase(""),true);
You can access the JVMs out put stream. We have done this with legacy code that unfortunately does not employ a logger, but prints all its information to System.out
For demonstration, have a look at this class that throws a given exception or none, if null is passed in the constructor. That thrown exception will be handled and printed to System.out, just like you explained in your question.
public class SystemOutClass {
private Exception exception;
public SystemOutClass(Exception exception) {
super();
this.exception = exception;
}
public Object doStuff() {
Object returnObject = null;
try {
doThrowException();
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return returnObject;
}
private void doThrowException() throws NoSuchMethodException,
InstantiationException, IllegalAccessException, InvocationTargetException,
Exception {
if (exception != null) {
throw exception;
}
}
}
The according test will switch the System.out to a known ByteArrayOutputStream, which then in turn can be checked for certain contents.
public class SystemOutTest {
private PrintStream defaultOutStream;
private ByteArrayOutputStream outStream;
#Before
public void setupStandardOutStream() {
outStream = new ByteArrayOutputStream();
defaultOutStream = System.out;
System.setOut(new PrintStream(outStream));
}
#After
public void cleanUpOutStream() {
System.setOut(defaultOutStream);
}
private String getConsoleOutput() {
return outStream.toString();
}
#Test
public void handleNoSuchMethodException() {
// given
SystemOutClass handlingClass = new SystemOutClass(new NoSuchMethodException());
// when
handlingClass.doStuff();
// then
getConsoleOutput().contains("java.lang.NoSuchMethodException");
}
}
If you have a specific part of a method that you'd like to test in isolation, refactor your class accordingly:
Object doSomeStuffAndPossiblyFail()
{
Object returnObject = null;
// do some stuff to set returnObject
return returnObject;
}
Object doSomeStuffAndReportFailureAsNull()
{
Object returnObject = null;
try {
returnObject = doSomeStuffAndPossiblyFail();
}
catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
....
return returnObject;
}
You're now free to test that doSomeStuffAndPossiblyFail completes without throwing any exceptions.

How to catch all exceptions except a specific one?

Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException) {
//can I throw this to the next level without eating it up in the last catch block?
} catch (Exception e) {
//default routine for all other exceptions
}
}
/Sidenote: the marked "duplicate" has nothing to do with my question!
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException se) {
throw se;
} catch (Exception e) {
//default routine for all other exceptions
}
}
you can do like this
try {
methodThrowingDifferentExceptions();
} catch (Exception e) {
if(e instanceof SpecificException){
throw e;
}
}

How to catch a thrown exception in the calling class

I got a method that throw an exception if I try to insert an existing object in DB.
public void addInDB() throws Exception {
if (isInBase()){
throw new Exception ("[ReqFamily->addInDB] requirment already in base");
}
int idParent = m_parent.getIdBdd();
idBdd = pSQLRequirement.add(name, description, 0, idParent,
ReqPlugin.getProjectRef().getIdBdd(), 100);
}
So when the exception is thrown I wanna catch it and display an error messsage in my managed bean.
PS: In my managed bean I just call the method :
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
ex.printStackTrace();
}
}
Its bad practice to catch or throw Exception. If any code you use throws a checked exception then just catch that specific exception, and try to minimize the size of your try-catch blocks.
class MyException extends Exception {
...
public void addInDB() throws MyException {
if (isInBase()){
throw new MyException ("[ReqFamily->addInDB] requirment already in base");
}
...
void addReq(Requirement req){
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
try {
req.addInDB();
} catch (MyException ex){
ex.printStackTrace();
}
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
}
Try this:
try {
req.addInDB();//here i want to catch it
} catch (Exception ex){
ex.printStackTrace();
}
You can try this:
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
If you wanna capture all of stacktrace to be show in display, you can use this:
catch (Exception ex) {
String
ls_exception = "";
for (StackTraceElement lo_stack : ex.getStackTrace()) {
ls_exception += "\t"+lo_stack.toString()+"\r\n";
}
JOptionPane.showMessageDialog(null, ls_exception);
}

Categories