我正在使用netbeans,我创建了这个异常类:
public class VehicleException extends Exception{
private String matricula;
private Calendar dataMatricula;
private ModelVehicle model;
private int causa;
public VehicleException(int causa, Object valor) throws Exception {
this.causa = causa;
switch (causa) {
case 1:
dataMatricula = (Calendar) valor;
break;
case 2:
matricula = (String) valor;
break;
case 3:
model = (ModelVehicle) valor;
break;
default:
throw new Exception("Utilització errònia en construir VehicleException. Causa: " + causa);
}
}
@Override
public String getMessage() {
switch (causa) {
case 1:
return "dataMatricula erroni: " + dataMatricula + " Ha de contenir valor";
case 2:
return "matricula erroni: " + matricula + " Ha de contenir valor";
case 3:
return "Model erroni: " + model + " Ha de contenir valor";
default:
return "";
}
}
Run Code Online (Sandbox Code Playgroud)
我正在我的班级"车辆"中处理这种异常:
public class Vehicle implements Comparable<Vehicle> {
private String matricula;
private ModelVehicle model;
private Calendar dataMatricula;
public Vehicle(String matricula, ModelVehicle model, Calendar dataMatricula) throws VehicleException {
setMatricula(matricula);
setDataMatricula(dataMatricula);
setModelVehicle(model);
}
public String getMatricula(){
return matricula;
}
public ModelVehicle getModelVehicle(){
return model;
}
public Calendar getDataMatricula(){
return dataMatricula;
}
public final void setMatricula(String matricula) throws VehicleException {
if (matricula == null || matricula.compareTo("") == 0) {
throw new VehicleException(2,matricula);
}
this.matricula = matricula;
}
public void setModelVehicle(ModelVehicle model) throws VehicleException{
if(model == null){
throw new VehicleException(3,model);
}
else {
this.model = model;
}
}
public void setDataMatricula(Calendar c) throws VehicleException{
if(c == null){
throw new VehicleException(1,c);
}
this.dataMatricula = c;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译时问题锥,在setter方法中我收到此消息:
错误:未报告的异常异常; 必须被捕获或声明被抛出新的VehicleException(2,matricula); C:\ Users\Ivan\Desktop\Examen isidrer\M03-uf5\Exmaenm03uf5\src\info\infomila\Vehicle.java:55:error:undported exception Exception; 必须被捕获或声明抛出新的VehicleException(3,model); C:\ Users\Ivan\Desktop\Examen isidrer\M03-uf5\Exmaenm03uf5\src\info\infomila\Vehicle.java:64:error:undported exception Exception; 必须被捕获或声明被抛出新的VehicleException(1,c);
我不太清楚为什么会发生这种情况,因为setter方法有一个"抛出VehicleException".
构造函数VehicleException可以自己抛出异常:
public VehicleException(int causa, Object valor) throws Exception {
^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
这意味着您的调用范围需要从构造函数处理/重新抛出该异常,或者您可以选择抑制异常而不是抛出异常.
default:
super.addSuppressed(new Exception("Utilització errònia en construir VehicleException. Causa: " + causa));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |