2011-07-19 100 views
3

我试图运行下面的代码处理,但我得到错误,请澄清我的疑问异常在Java

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"); 
        ^

1错误

+0

我不知道为什么我不能编辑甚至因重新打这个问题 –

+0

@eng有人用低于2000的声誉已经编辑了该问题,并且编辑尚未获得具有较高声誉的用户的批准。 –

+0

或者,您可以按如下所示抛出异常:'new Except()。new AlphaException();'。 –

回答

5

静态上下文是在没有该类的实际实例的情况下在类上运行的上下文。你的主要方法是静态的,这意味着它只能访问静态变量。但是,您的AlfaException是而不是静态。这意味着它将被绑定到Except类的实例 - 您没有。

因此,你有2点,选项:

  1. 让AlfaException也是静态的:public static class AlfaException extends Exception{}。这将使它驻留在静态作用域中,以便可以从静态函数访问它。
  2. 将所有的main(...)方法逻辑转移到非静态上下文中。创建一个名为doWork()函数,也不是一成不变的,把所有的代码maindoWork,然后调用它像这样:

public static void main(String[] args) { 
    Except instance = new Except(); 
    instance.doWork(); 
} 
3

你AlfaException是一个非静态内部类的除外,所以它只能从例外实例实例化。主要的方法是静态的,所以没有封闭的实例。

变化AlfaException的声明:

public static class AlfaException extends Exception{} 

,它应该工作。

0

有几个错误:

  1. AlfaExceptiontry - 块是从来没有抛出
  2. AlfaException是一个非静态内部类的Except(见其他答案)
  3. 如果您在catch区块中重新引用AlfaException,则main需要throws,如下所示:

    public static void main(String[] args) throws AlfaException { ... 
    
0
import java.util.*; 

class Except 
{ public static class AlfaException extends Exception{ 

    public AlfaException(String string) { 
     super(); 
    } 
} 
    public static void main(String[] args) throws AlfaException 
    { 

    int b; 
    Scanner s=new Scanner(System.in); 
     try 
     { 
      System.out.println("Enter the value for b"); 
      b=s.nextInt(); 
      System.out.println("b value is "+b); 
     } 
     catch(InputMismatchException ex) 
      { 
      if(('b'> 67)&&('b'<83)){}   
      System.out.println("error found"); 
      } 
    } 
} 

输出:
为b输入值
80B
发现错误