1、首先自定义异常类继承Exception类,如以下代码
public class MyException extends Exception {
private String Commands;
public MyException{
super();
}
public MyException(String Commands){
super(Commands);
this.Commands = Commands;
}
2.使用throws关键字在要抛出异常的函数
public class UseMyException {
private String name;
private String message;
public UseMyException(String name,String message){
this.name = name;
this.message = message;
}
public void throwException(String message) throws MyException{
if (this.message!=message){
throw new MyException("密码不正确!");
}
}
}