异常Exception类 + Complex类

java内部已经定义了很多异常,这些异常分为两大类:运行时异常类 和 非运行时异常类。它们的继承结构如下图:
在这里插入图片描述
常见的异常有:
ArithmeticException 算术异常
ArrayIndexOutOfBoundsException数组下标越界异常
ClassCastException类型转换异常
NullPointerException空指针异常

对于异常,有两种处理方式(能处理处理,不能处理就抛出):
a、try-catch

try {
可能出现问题的代码 ;
} catch(异常名 变量名) {
针对问题的处理 ;
} finally {
释放资源;
}
b、抛出
throws
用在方法声明后面,跟的是异常类名
可以跟多个异常类名,用逗号隔开
表示抛出异常,由该方法的调用者来处理
throws表示出现异常的一种可能性,并不一定会发生这些异常
throw
用在方法体内,跟的是异常对象名
只能抛出一个异常对象名
这个异常对象可以是编译期异常对象,可以是运行期异常对象
表示抛出异常,由方法体内的语句处理
throw则是抛出了异常,执行throw则一定抛出了某种异常

不仅如此,我们还可以根据自己的需要,生成自己的异常类,这极大地扩展了异常的应用范围,方便了软件开发。
我们可以通过eclipse来帮助我们快速建立一个异常类:

在这里插入图片描述
然后再选择添加缺省串行版本标识,就能生成一个序列号。
在这里插入图片描述
先使用eclipse工具帮助我们定义两个异常类:

public class ComplexDividedByZeroRuntimeException extends RuntimeException
{

    private static final long serialVersionUID=1L;

    public ComplexDividedByZeroRuntimeException()
    {}

    public ComplexDividedByZeroRuntimeException(String message)
    {
        super(message);
    }

    public ComplexDividedByZeroRuntimeException(Throwable cause)
    {
        super(cause);
    }

    public ComplexDividedByZeroRuntimeException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public ComplexDividedByZeroRuntimeException(String message, Throwable cause, boolean enableSuppression,
            boolean writableStackTrace)
    {
        super(message, cause, enableSuppression, writableStackTrace);
    }

}

public class ComplexDividedByZeroException extends Exception
{

    private static final long serialVersionUID=1L;

    public ComplexDividedByZeroException()
    {}

    public ComplexDividedByZeroException(String message)
    {
        super(message);
    }

    public ComplexDividedByZeroException(Throwable cause)
    {
        super(cause);
    }

    public ComplexDividedByZeroException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public ComplexDividedByZeroException(String message, Throwable cause, boolean enableSuppression,
            boolean writableStackTrace)
    {
        super(message, cause, enableSuppression, writableStackTrace);
    }

}

再提供一个SimpleClass类

public class SimpleClass
{
    public SimpleClass()
    {}

    public int fun1(int num)
    {
        if(num < 10)
        {
            throw new ComplexDividedByZeroRuntimeException("发生了运行时异常!");
        }
        return num + 1;
    }

    public int fun2(int num) throws ComplexDividedByZeroException
    {
        if(num < 10)
        {
            throw new ComplexDividedByZeroException("发生了 非 运行时异常");
        }
        return num + 2;
    }

}

运行结果如下:
在这里插入图片描述
在这里插入图片描述
除零错也是一个很经典的异常,我们通过一个小例子来展示如何处理除零错:
编写一个Complex类,要求实现:
1、复数的加减乘除;
2、无参、单参、双参、对象构造法;
3、用两种方式实现加法:c=a+b a+=b;
4、减法用加法实现,除法用乘法实现;
5、解决除零错误。

首先给出一个Complex类:

import java.util.Objects;

public class Complex
{
    private double real;
    private double vir;

    public Complex(double real, double vir)
    {
        this.real=real;
        this.vir=vir;
    }

    public Complex(double real)
    {
        this(real, 0.0);
    }

    public Complex(Complex complex)
    {
        this(complex.real, complex.vir);
    }

    public Complex()
    {
        this(0.0, 0.0);
    }

    // a = b + c
    public static Complex add(Complex one, Complex other)
    {
        return new Complex(one.real + other.real, one.vir + other.vir);
    }

    // a += b;
    public Complex add(Complex one)
    {
        return add(this, one);
    }

    // a = b - c
    public static Complex decrease(Complex one, Complex other)
    {
        return add(one, new Complex(-other.real, -other.vir));
    }

    // a -= b
    public Complex decrease(Complex one)
    {
        return decrease(this, one);
    }

    // a = b * c
    // (a + bi) * (c + di) = ac - bd + (ad + bc)i
    public static Complex mul(Complex one, Complex other)
    {
        return new Complex(one.real * other.real - one.vir * other.vir, one.real * other.vir + one.vir * other.real);
    }

    // a *= b
    public Complex mul(Complex one)
    {
        return mul(this, one);
    }

    // 取倒数
    // 1 / (a + bi) = (a - bi) / (a + bi) * (a - bi) = (a - bi) / (a*a + b*b)
    private static Complex collapse(Complex one) throws Exception
    {
        double lin=one.real * one.real + one.vir * one.vir;
        if(lin == 0.0)
        {
            throw new ThrowException("除0错");
        }

        return new Complex(one.real / lin, -one.vir / lin);
    }

    // a = b / c
    public static Complex div(Complex one, Complex other) throws Exception
    {
        Complex result=mul(one, collapse(other));
        return result;
    }

    // a /= b
    public Complex div(Complex one) throws Exception
    {
        return div(this, one);
    }

    @Override
    public boolean equals(Object o)
    {
        if(this == o)
            return true;

        if(o == null || getClass() != o.getClass())
            return false;

        Complex complex=(Complex) o;
        return Double.compare(complex.real, real) == 0 && Double.compare(complex.vir, vir) == 0;
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(real, vir);
    }

    @Override
    public String toString()
    {
        return "(" + this.real + "," + this.vir + "i)";
    }
}

自定义异常,用来处理除0错误:

public class ThrowException extends RuntimeException
{
    private static final long serialVersionUID=1L;

    public ThrowException()
    {
        super();
    }

    public ThrowException(String message)
    {
        super(message);
    }

    public ThrowException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public ThrowException(Throwable cause)
    {
        super(cause);
    }

    protected ThrowException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
    {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

用一个Test来测试一下

public class Test
{
    public static void main(String[] args) throws Exception
    {
        System.out.print("创建第一个数:");
        Complex one=new Complex(3.0);
        System.out.println(one);
        System.out.print("创建第二个数:");
        Complex two=new Complex(3.0, 5.0);
        System.out.println(two);

        Complex sum=one.add(two);
        System.out.println("加法:" + sum);
        Complex decrease=one.decrease(two);
        System.out.println("减法:" + decrease);
        Complex mul=one.mul(two);

        System.out.println("乘法:" + mul);
        Complex div=one.div(new Complex(0, 0));
        System.out.println("除法:" + div);
    }
}

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我来实现这个方法: ```java public class Complex { private double real; private double imag; // 构造方法 public Complex(double real, double imag) { this.real = real; this.imag = imag; } // 复数加法 public Complex add(Complex c) { return new Complex(this.real + c.real, this.imag + c.imag); } // 复数减法 public Complex sub(Complex c) { return new Complex(this.real - c.real, this.imag - c.imag); } // 复数乘法 public Complex mul(Complex c) { return new Complex(this.real * c.real - this.imag * c.imag, this.real * c.imag + this.imag * c.real); } // 复数除法 public Complex div(Complex c) throws Exception { if (c.mod() == 0) { throw new Exception("The modulus of the complex divided cannot be zero!"); } double real = (this.real * c.real + this.imag * c.imag) / c.mod(); double imag = (this.imag * c.real - this.real * c.imag) / c.mod(); return new Complex(real, imag); } // 复数模 public double mod() { return Math.sqrt(this.real * this.real + this.imag * this.imag); } // 复数字符串表示 public String toString() { if (this.imag >= 0) { return this.real + "+" + this.imag + "i"; } else { return this.real + "-" + (-this.imag) + "i"; } } } ``` 这里,我们新增了一个 `div` 方法,用于计算两个复数的除法。如果被除数的模为 0,则抛出一个异常。否则,我们按照公式计算出商的实部和虚部,并构造一个新的 `Complex` 对象返回。 为了方便计算,我们还新增了一个 `mod` 方法,用于计算复数的模。 现在,我们可以在其他的中使用这个 `div` 方法了,如下所示: ```java Complex c1 = new Complex(1, 2); Complex c2 = new Complex(3, 4); try { Complex c3 = Complex.div(c1, c2); System.out.println(c3); } catch (Exception e) { System.out.println(e.getMessage()); } ``` 这段代码会输出 `0.44+0.08i`,表示两个复数相除的结果。如果我们将 `c2` 的虚部改为 0,则会抛出一个异常,输出 `The modulus of the complex divided cannot be zero!`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值