创建自定义机器人命令异常
- Updated: 2023/05/08
您可以使用 BotCommandException
类创建用于错误报告的自定义机器人命令异常。 您可以在您的方法中抛出和捕获它们。 通过自定义异常,您可以指定详细的错误消息,并在捕获块中进行更多自定义的错误处理。
示例: 定义一个自定义的 BotCommandException
此示例定义了一个名称为 DemoException 的自定义异常。 该类扩展了 BotCommandException,并通过调用超类中的等量构造函数实现多个构造函数。 您只需实现您想使用的构造函数,而可以忽略超类中的其他构造函数(Java 类不继承构造函数,因此您必须重新实现)。
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); } }
BotCommandException 类的许多构造函数接受一个 java.lang.Throwable 对象作为参数。 如果您希望自定义异常,以包含导致该异常的异常,可以实现类似的构造函数,并将 Throwable 对象(通常是其他异常对象)传递给自定义异常。
以下示例展示了如何使用您在上一个示例中定义的异常。
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; }
如果发现异常,就会捕获异常,并通过示例中定义的错误语句进行处理。