Java如何使用重载方法处理异常?

在Java编程中,如何使用重载方法处理异常?

此示例显示如何使用重载方法来处理异常。需要在每个方法中使用try catch块。

package com.yiibai;

public class ExceptionWithOverloadedMethods {
    double method(int i) throws Exception {
        return i / 0;
    }

    boolean method(boolean b) {
        return !b;
    }

    static double method(int x, double y) throws Exception {
        return x + y;
    }

    static double method(double x, double y) {
        return x + y - 3;
    }

    public static void main(String[] args) {
        ExceptionWithOverloadedMethods mn = new ExceptionWithOverloadedMethods();
        try {
            System.out.println(method(110, 120.0));
            System.out.println(method(110.0, 120));
            System.out.println(method(110.0, 120.0));
            System.out.println(mn.method(110));
        } catch (Exception ex) {
            System.out.println("exception occoure: " + ex);
        }
    }
}
Java

上述代码示例将产生以下结果 -

230.0
227.0
227.0
exception occoure: java.lang.ArithmeticException: / by zero
Shell

示例-2

以下是在Java中使用重载方法处理异常的另一个示例

package com.yiibai;

class NewClass1 {
    void msg() throws Exception {
        System.out.println("this is parent");
    }
}

public class ExceptionWithOverloadedMethods2 extends NewClass1 {
    ExceptionWithOverloadedMethods2() {
    }

    void msg() throws ArithmeticException {
        System.out.println("This is child");
    }

    public static void main(String args[]) {
        ExceptionWithOverloadedMethods2 n = new ExceptionWithOverloadedMethods2();
        try {
            n.msg();
        } catch (Exception e) {
        }
    }
}
Java

上述代码示例将产生以下结果 -

This is child
原文地址:https://www.cnblogs.com/borter/p/9613539.html