Create a custom bot command exceptions
- Updated: 2023/05/08
Create a custom bot command exceptions
You can use the BotCommandException
class to create a custom Bot
Command Exceptions for error reporting. You can throw and catch them in your methods. With
custom exceptions, you can specify detailed error messages and have more custom error
handling in your catch blocks.
Example: Define a custom BotCommandException
This example defines a custom exception called DemoException. This class extends BotCommandException and implements several constructors by invoking the equivalent amount of constructors in the super-class. You only need to implement the constructors that you want to use, and you can ignore the rest of the constructors in the super-class (Java classes do not inherit constructors, so you must re-implement them).
package com.automationanywhere.botcommand.samples.exceptions;
import com.automationanywhere.botcommand.data.Value;
import com.automationanywhere.botcommand.exception.BotCommandException;
import java.util.Optional;
public class DemoException extends BotCommandException {
public DemoException(String message, Throwable cause) {
super(message, cause);
}
public DemoException(String message) {
super(message);
}
public DemoException(Throwable cause) {
super(cause);
}
public DemoException(String message, Throwable cause, Optional<Value> outputVariables) {
super(message, cause, outputVariables);
}
}
Many constructors of the BotCommandException class accept a java.lang.Throwable object as an argument. You can implement similar constructors and pass Throwable objects (usually other exception objects) to your custom exceptions when you want your custom exception to include the exception that caused it.
The following example shows how to use the exception that you defined in the previous example.
public static boolean checkRecordsExist(Connection con, String query)
throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
rs.last();
if(rs.getRow() > 0)
return true;
} catch (SQLException e ) {
throw new DemoException("Problem running statement", e);
} finally {
if (stmt != null) { stmt.close(); }
}
return false;
}
If an exception is found, then this would catch the exception and through an error statement as defined in the example.