使用java中的throw来处理异常

时间:2012-12-10 10:01:38

标签: java exception-handling throw

我有以下代码行,其中fetchData()方法给出了SQLException(无效的标识符)。现在我将错误抛给ErrorInQuery类。

 try{                       
        ResultSet rsObj = connect.fetchData(query);     
        }catch(Exception ex){       
        throw new ErrorInQuery("Query is wrong");
        }

在ErrorInQuery类中,我喜欢

public class ErrorInQuery extends Exception {

    private static final long serialVersionUID = 1L;
    String msg = "";

    public ErrorInQuery() {
    }

    public ErrorInQuery(String msg) {
        super(msg);
    }

    public String toString() {
        msg = "Your Query is wrong!";
        return msg;
    }
}

但无法处理异常。我在代码中缺少什么东西。

1 个答案:

答案 0 :(得分:1)

此代码的处理方式如下:

try{                       
    ResultSet rsObj = connect.fetchData(query);     
    }catch(Exception ex){       
    throw new ErrorInQuery("Query is wrong");
    }

需要在方法语句中包含throws声明: 例如

public void fetchData() throws ErrorInQuery { }