加载方法的自定义异常

时间:2015-08-17 08:55:37

标签: java exception serialization exception-handling custom-exceptions

我创建了一个自定义异常,这样当我浏览文件并关闭浏览器时,我会发现错误并告诉用户"请选择一个文件":

if (entry.Entity is Request|| entry.Entity is Material)
{
    var myEntity = entry.Entity;
    ctx.LoadProperty(myEntity.RevisedBy, x => x.Roles);
    if (myEntity.RevisedBy.Roles.Find(x => x.RoleName == "ADMIN") == null) return;
}

现在我尝试在load方法中输入它,但我无法看到我可以输入它的位置,因为netbeans已经自动生成了多个异常:

public class CancelException extends Exception {

    public CancelException() {
    }

    public CancelException(String message) {
        super(message);
    }

}

任何对此的帮助都会非常感激,因为我是这种语言的初学者。

我尝试在load方法中创建异常:

public static Person loadcons() throws IOException
{
    Person loadcons = null;
    JFileChooser chooser = new JFileChooser();
    int chooserOption = chooser.showSaveDialog(null);
    chooserOption = JFileChooser.APPROVE_OPTION;

    try {
        File file = new File (chooser.getSelectedFile().getAbsolutePath());
        ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
        loadcons = (Person) input.readObject();
        input.close();
        return loadcons;
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    } catch (ClassNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
    return null;

}

private String toString(String PersonID) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

但是没有抛出异常

1 个答案:

答案 0 :(得分:0)

我想在下面建议您使用自定义异常 -

import *.CancelException;

public static Person loadcons() throws IOException,CancelException 
  ..
  ..
try {
    ..
    ..
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    } catch (ClassNotFoundException ex) {
    System.out.println(ex.getMessage());
    }catch (Exception ex) {
        throw new CancelException("Please select a file");
   }
    return null;