IMPORTANT: This question only relates to Java 6 (and below).

The hierarchy here shows Java Exceptions are divided into two types: RuntimeException and [not a RuntimeException]:

Java exceptions hierarchy

Would it not have been better to divide into something like UncheckedException and CheckedException instead? For example, the following statement has quite a few checked exceptions:

try {
    transaction.commit();
} catch (SecurityException e) {
} catch (IllegalStateException e) {
} catch (RollbackException e) {
} catch (HeuristicMixedException e) {
} catch (HeuristicRollbackException e) {
} catch (SystemException e) {
}

Am only really interested in whether it succeeds or fails so would like to deal with the checked exceptions as a group but not the unchecked exceptions as it's not good practice to catch an unexpected error. So with this in mind, maybe I could do something like:

try {
    transaction.commit();
} catch (Exception e) {
    if (e instanceof RuntimeException) {
        // Throw unchecked exception
        throw e;
    }
    // Handle checked exception
    // ...
}

But this seems horribly hacky. Is there a better way?

有帮助吗?

解决方案

If I understood correctly, then you are almost there. Just catch RuntimeException. That will catch RuntimeException and everything under it in the hierarchy. Then a fallthrough for Exception, and you're covered:

try {
    transaction.commit();
} catch (RuntimeException e) {
    // Throw unchecked exception
    throw e;
} catch (Exception e) {
    // Handle checked exception
    // ...
}

其他提示

Java 7 allows you such constructions:

try {
    transaction.commit();
} catch (SecurityException | IllegalStateException  | RollbackException | HeuristicMixedException  e ) {
   // blablabla
}

UPD: I think, that there isn't nice and convenient way for doing it in earlier versions of Java. That is why developers of Java language introduced such construction in Java 7. So, you could devise your own approaches for Java 6.

I gave a similar answer in another post, so yes, it is copy past:

Something that I do is to have a static method that handles all exceptions and I add the log to a JOptionPane to show it to the user, but you could write the result to a file in FileWriter wraped in a BufeeredWriter. For the main static method, to catch the Uncaught Exceptions I do:

SwingUtilities.invokeLater( new Runnable() {
    @Override
    public void run() {
        //Initializations...
    }
});


Thread.setDefaultUncaughtExceptionHandler( 
    new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException( Thread t, Throwable ex ) {
            handleExceptions( ex, true );
        }
    }
);

And as for the method:

public static void handleExceptions( Throwable ex, boolean shutDown ) {
    JOptionPane.showMessageDialog( null,
        "A CRITICAL ERROR APPENED!\n",
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE );

    StringBuilder sb = new StringBuilder(ex.toString());
    for (StackTraceElement ste : ex.getStackTrace()) {
        sb.append("\n\tat ").append(ste);
    }


    while( (ex = ex.getCause()) != null ) {
        sb.append("\n");
        for (StackTraceElement ste : ex.getStackTrace()) {
            sb.append("\n\tat ").append(ste);
        }
    }

    String trace = sb.toString();

    JOptionPane.showMessageDialog( null,
        "PLEASE SEND ME THIS ERROR SO THAT I CAN FIX IT. \n\n" + trace,
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE);

    if( shutDown ) {
        Runtime.getRuntime().exit( 0 );
    }
}

In you case, instead of "screaming" to the user, you could write a log like I told you before:

String trace = sb.toString();

File file = new File("mylog.txt");
FileWriter myFileWriter = null;
BufferedWriter myBufferedWriter = null;

try {
    //with FileWriter(File file, boolean append) you can writer to 
    //the end of the file
    myFileWriter = new FileWriter( file, true );
    myBufferedWriter = new BufferedWriter( myFileWriter );

    myBufferedWriter.write( trace );
}
catch ( IOException ex1 ) {
    //Do as you want. Do you want to use recursive to handle 
    //this exception? I don't advise that. Trust me...
}
finally {
    try {
        myBufferedWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }

    try {
        myFileWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }
}

I hope I have helped.

Have a nice day. :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top