Java - 自定义异常(尚学堂第六章作业判断三角形)

写一个方法void isTriangle(int a,int b,int c),判断三个参数是否能构成一个三角形, 如果不能则抛出异常IllegalArgumentException,显示异常信息 “a,b,c不能构成三角形”,如果可以构成则显示三角形三个边长,在主方法中得到命令行输入的三个整数, 调用此方法,并捕获异常。

import java.util.Scanner;

public class TestTriangle {
    public static void main(String[] args) {
        System.out.print("请输入a, b, c:");
        Scanner input = new Scanner(System.in);
        int a = input.nextInt();
        int b = input.nextInt();
        int c = input.nextInt();

        isTriangle(a, b, c);
        
    }
    
    static void isTriangle(int a, int b, int c) {
        if(a+b<c||a+c<b||b+c<a) {
                try {
                    throw new IllegalAgeException("a,b,c不能构成三角形");
                }catch(Exception e) {
                    e.printStackTrace();
                }
        }else {
            System.out.println("a, b, c构成三角形");
        }
    }
}

class IllegalArgumentException extends Exception{

    public IllegalArgumentException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public IllegalArgumentException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }
    
}

猜你喜欢

转载自www.cnblogs.com/kl-1998/p/10694048.html