package homework6;import java.util.Scanner;
import java.util.InputMismatchException;
public class Test { public static void main(String[] args) {
try{
foo();
}catch(MyStrChkException e){
System.out.println("触发自定义异常!");
System.out.println(e.getContent());
}catch(InputMismatchException e){
System.out.println("数字格式异常");
}catch(Exception e){
System.out.println("程序结束!");
}
}
public static void foo()throws MyStrChkException{
Scanner input = new Scanner(System.in);
double y, c;
System.out.println("请输入除数");
y=input.nextInt();
if(y==0){
input.close();
throw new MyStrChkException("除数不能为0");
}
c=10/y;
System.out.println("10/y="+c);
input.close();
}
class MyStrChkException extends Exception{
private static final long serialVersionUID=1L;
private String content;
public MyStrChkException(String content){
this.content = content;
}
public String getContent(){
return content;
}
}
}

解决方案 »

  1.   

    因为你的MyStrChkException是一个Test的内部类,地位就相当于一个成员变量,而main方法是static方法,static方法不能直接方法非static的成员变量或方法这你应该是知道的吧,所以修改方法有以下几种:
    1、在class MyStrChkException{....}的class前面加上static,将其声明为static的成员,main方法就可以直接访问了。
    2、throw new MyStrChkException("除数不能为0");改为throw new Test().new MyStrChkException("除数不能为0");
    同样是针对static关键字的修改方式,先new一个Test类的对象,再通过这个对象new出它的内部类的实例对象
    3、直接将MyStrChkException定义为外部类。