Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

java - When to use catch and when to use throws in the exception handling

The question is not about exception handling syntax, but it is all about which is the right place to write catch block for an exception in its journey over methods through propagation.

public boolean validateUser(String username, String password) throws SQLException {
    Connection conn = dataSource.getConnection();
    boolean result = false;
    PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE   USERNAME=? AND PASSWORD=?");
    pstmt.setString(1, username);
    pstmt.setString(2, password);
    result = pstmt.executeQuery().next();
    conn.close();
    return result;
}

Assume method1() called method2() and method2() called above method. In the above method if I handle the exception, I have to return a value. Let's assume that I have returned false after catch block, method2() misunderstands like the username or password is wrong.

If I am not handling, method2() will not receive any value and it's catch block will execute and the same problem would occur in method1().

Now can you define where can I effectively handle the exception?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should catch an exception only if you can reasonably recover from the error condition. In every other case, you should propagate it up to your caller and hope that he might be able to handle it in a meaningful way. If nobody up the call stack will be able to handle it, termination of the application is probably the correct thing to happen.

Suppose you are writing a graphical user interface with icons. You have one method

Icon loadIcon(String filename) throws IOException;

that loads the icon's image from a disk file. If this I/O operation fails, there is no obvious way loadIcon could recover from that error. It is probably best to let the exception propagate.

Somewhere else, you have another method

void buildGUI();

that populates the user interface. It will make use of loadIcon to get icons for the various buttons based on the currently selected icon theme. If loading one icon fails, this would be a poor reason to crash the whole GUI building process. Here, we should probably catch the exception and try using a fallback icon or display an empty button. This will allow the user to still use the application and perhaps realize that some icons are missing and thus go and fix their installation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...