我试图运行以下代码,但我收到错误请澄清我的疑问
import java.util.*;
class Except
{ public class AlfaException extends Exception{}
public static void main(String[] args)
{
int b;
Scanner s=new Scanner(System.in);
try
{
b=s.nextInt();
}
catch(InputMismatchException ex)
{
try
{
if(('b'> 67)&&('b'<83)){}
}
catch(AlfaException e){
throw new AlfaException("hello");
}
System.out.println("error found");
}
}
}
Except.java:20: non-static variable this cannot be referenced from a static cont
ext
throw new AlfaException("hello");
^
Run Code Online (Sandbox Code Playgroud)
1错误
静态上下文是在没有该类的实际实例的类上运行的上下文.您的main方法是静态的,这意味着它只能访问静态变量.但是,您的AlfaException 不是静态的.这意味着它将会被绑定到一个实例的Except类-你没有.
因此,您有2个选择:
public static class AlfaException extends Exception{}.这将使它驻留在静态范围内,因此可以从静态函数访问它.main(...)方法逻辑移动到非静态上下文中.创建一个名为doWork()不是静态的函数,将所有代码main移到doWork,然后像这样调用它:.
public static void main(String[] args) {
Except instance = new Except();
instance.doWork();
}
Run Code Online (Sandbox Code Playgroud)