Home > Blockchain >  How can I ask whether a function throws an exception within my if statement clause?
How can I ask whether a function throws an exception within my if statement clause?

Time:05-15

I'm trying to write code that checks if several different options returns an Exception:

// Checks if a given Item can move
// @param fromRow
// @param fromCol
// @return A Boolean that tells us if the given space can move
private boolean canMove(int fromRow, int fromCol){
if((move(fromRow,fromCol,fromRow-2,fromCol) ||
   move(fromRow,fromCol,fromRow 2, fromCol) ||
   move(fromRow,fromCol,fromRow,fromCol-2) ||
   move(fromRow, fromCol,fromRow,fromCol 2)) throws Exception){
   return true;
}
  

}

CodePudding user response:

Easy solution with a try and catch block:

private boolean canMove(int fromRow, int fromCol){
    try{
       move(fromRow,fromCol,fromRow-2,fromCol);
       move(fromRow,fromCol,fromRow 2, fromCol);
       move(fromRow,fromCol,fromRow,fromCol-2);
       move(fromRow, fromCol,fromRow,fromCol 2));
    } catch (Exception e){
        return true;
    }
   return false;

I am unsure about what the method move actually does, so this might not work for you. You should also check which kind of exception you get from move and only check for that.

CodePudding user response:

I interpret the problem as "return true if any of the 4 moves is possible, otherwise false". Right?

To avoid sprawl, I add a secondary method for a single move, catching any possible exception and converting it to a false return.

You don't actually need an 'if' statement; the short-circuiting logical-or operator will return the value you need to return.

private boolean canMove(int fromRow, int fromCol){
    return tryMove(fromRow, fromCol,fromRow-2,fromCol) ||
           tryMove(fromRow, fromCol,fromRow 2, fromCol) ||
           tryMove(fromRow,fromCol,fromRow,fromCol-2) ||
           tryMove(fromRow, fromCol,fromRow,fromCol 2);
}

private boolean tryMove(int w, int x, int y, int z) {
   try {
      return move(w, x, y, z);
   }
   catch (Exception ex) {
       return false;
   }
}

CodePudding user response:

NOTE: response to this comment, not a full answer

Am I allowed to use multiple try catch blocks within one function? I am still a little confused on how I would implement that in an if statement. -- @ Dheeraj Valluru

This is the Parent of all Exceptions, so nothing will get past it:

catch(Exception exc)

Making different try-catch blocks to specify where the issue is coming from could be done with ^this^. If you wanted to make it even more specific -- which exceptions you are testing for -- you can use the | (or) syntax with the actual Exception class names:

// random example Exceptions
catch(NumberFormatException | NullPointerException invalid)
  • Related