Java 异常

2021/7/26 17:09:14

本文主要是介绍Java 异常,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

声明异常:throws

抛出异常:throw

public class CircleWithExceptionTest {
    public static void main(String[] args){
        try{
            CircleWithException c1 = new CircleWithException(5);
            CircleWithException c2 = new CircleWithException(-5);
            CircleWithException c3 = new CircleWithException(0);
        }
        catch(IllegalArgumentException ex){
            System.out.println(ex);
        }
        System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects());
    }
}

class CircleWithException{

    private double radius;
    private static int numberOfObjects = 0;

    public CircleWithException(){
        this(1.0);
    }

    public CircleWithException(double newRadius){
        setRadius(newRadius);
        numberOfObjects ++;
    }

    public void setRadius(double newRadius) throws IllegalArgumentException{
        if(newRadius >= 0)
            radius = newRadius;
        else
            throw new IllegalArgumentException("Radius cannot be negative");
    }

    public double getRadius(){
        return radius;
    }

    public static int getNumberOfObjects(){
        return numberOfObjects;
    }

    public double findArea(){
        return (radius * radius * 3.14159);
    }
}

// 运行结果
/*
java.lang.IllegalArgumentException: Radius cannot be negative
Number of objects created: 1
 */
public class DivideException {

    public static void main(String[] args){
        compute();
    }

    public static void compute(){
        try{
            divide(5,0);
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }

    public static void compute2() throws Exception{
        divide(5,0);
    }

    public static void divide(int a, int b) throws Exception{
        if(b == 0){
            throw new Exception("两数相除,除数不能为0!");
        }
        else{
            System.out.println("The result is " + (a/b) );
        }
    }
}

// 运行结果
/*
两数相除,除数不能为0!
 */



这篇关于Java 异常的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程