• 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
  • 相关阅读:
    函数名的应用/列表推导式
    装饰器/内置函数
    函数的基础
    文件的改的操作
    常用str
    python 定时器 timer QTimer
    Python 2.7.16 pyinstaller3.0 生成exe可执行文件
    python 根据excel单元格内容获取该单元格所在的行号
    python 实现仪器LAN口通信(FLUKE 8846)
    VS2019 MSB8041 MSB8042 Error
  • 原文地址:https://www.cnblogs.com/borter/p/9613539.html
Copyright © 2020-2023  润新知