在java中使用关键字throw获取错误

时间:2014-12-15 04:17:43

标签: java try-catch

import java.io.*;
class A {
     private static final int x = 5;
     private int y;
     A(int z)
     {
       y = z;
     }

     public void f()
     {
        if(y<=x)
        {
           throw(-1);
        }
     }
}


public static void main(String args [])
{
      A a = new A(2);
      try (a.f();)
      catch (int i){
          System.out.println("exception");
          }   
}

我对java很新,并且正在尝试学习异常处理。我只是想知道这种方法有什么问题,因为我收到了错误,我该怎么办?

2 个答案:

答案 0 :(得分:1)

请参阅以下代码。

1。)try (a.f();)语法错误,请参阅下面的内容。

2。)throw(-1);应该抛出异常。

3.)方法应该catch or throws例外

public class A{
    private static final int x = 5;
    private final int        y;

    A(int z) {
        y = z;
    }

    public void f() throws Exception {
        if (y <= x) {
            throw new Exception();
        }
    }

    public static void main(String args[]) {
        A a = new A(2);
        try {
            a.f();
        } catch (Exception e) {
            System.out.println("exception");
        }
    }
}

答案 1 :(得分:1)

你做错了,找到下面的示例代码:

class Foo {
  private int bar;
  public void setBar(int bar) {
    if(0 > bar)//raise exception here
      throw new IllegalArgumentException("Invalid bar value: " + bar);
    this.bar = bar;//set the bar value
  }
  public int getBar() {
    return bar;
  }
}

class Demo {
  public static void main(String[] args) {
    Foo foo = new Foo();
    try {
      foo.setBar(34);
      System.out.println("bar is: " + foo.getBar());
      foo.setBar(-23);
      System.out.println("next bar is: " + foo.getBar());
    } catch (IllegalArgumentException ex) {//handle the exception here
       ex.printStackTrace(System.err);
    }
  }
}