java——指定方法抛出异常

2019年2月17日14:07:25 发表评论 1,154 views
/**
 * Created by xabcd on 2019/2/17.
 */
public class java_waythrow
{
    static class throwss

    {
        void add( int a, int b)throws Exception
        {
            int c;
            c = a / b;
            System.out.println(a / b);
        }
    }
    public static void main(String args[])
    {
        throwss t = new throwss();
        try {
            t.add(4,0);
        }
        catch (Exception e)
        {
            System.out.println(e);
        }
    }
}




从 编译 结果 中 可以 看到, 如果 在 类 的 方法 中用 throws 抛出 一个 异常, 那么 在调 用 它的 地方 就必须 明确 地 用 try- catch 来 捕捉。 提   示: 在 TestException_ 5 程序 之中, 如果 在 main() 方法 的 后面 再用 throws Exception 声明 的 话, 那么 程序 也是 依然 可以 编译 通过 的。 也就是说 在 调用 throws 抛出 异常 的 方法 时, 可以 将此 异常 在 方法 中 再向 上 传递, 而 main() 方法 是 整个 程序 的 起点, 所以 在 main() 方法 处 如果 再用 throws 抛出 异常, 则 此 异常 就 将 交由 JVM 进行 处理。

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: