zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Python的未来发展方向
    loadrunner分析之网页、网络、资源分析
    Django框架Day2之Template
    Django框架Day3之Models
    Appium 常用的API函数
    Django框架Day1之url和views
    Loadrunner常用分析点
    WEB性能测试用例设计
    python之高阶函数map()和reduce()
    python csv文件打开错误:_csv.Error: line contains NULL byte
  • 原文地址:https://www.cnblogs.com/borter/p/9613539.html
Copyright © 2011-2022 走看看