Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How can I avoid using try catch statements

Tags:

java

try-catch

I would like to know how I can avoid try-catch statements. Right now I have a Database handler and every time I run a command I have to surround it in a try block like so:

try {
    while(levelData.next()) {
        if(levelData.getInt("level") == nextLevel) return levelData.getInt("exp");
    }
} catch (SQLException e) {
    e.printStackTrace();
}   

Can I make it so the actual function throws the exception or something? Rather than having to manually put all these try's in? Its mostly just an aesthetic problem as these try blocks look ugly.

like image 874
Kyle Jensen Avatar asked Jun 08 '26 14:06

Kyle Jensen


1 Answers

You can throw an exception instead:

public void myMethod() throws SQLException {
     while(levelData.next()) {
        if(levelData.getInt("level") == nextLevel)
           return levelData.getInt("exp");
    }
}
like image 196
Lucas Baizer Avatar answered Jun 10 '26 04:06

Lucas Baizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!