首页 > 解决方案 > 我应该如何处理构造函数抛出的异常

问题描述

我遇到过这个问题:

我正在制作一个对象,比如说,Person;

public class Person
{
    public Person(String name, int age)
    {
        if (age < 0)
        {
            throw new AgeException("Age can not be lesser than 0");
        }
    }
}

对象的每次初始化都意味着我必须处理一个 try-catch 块。对我来说似乎有点不对,比如:

public static main(String[] args)
{
    try
    {
        Person p = new Person("SwagiWagi", 18);
    }
    catch (AgeException ex)
    {
        int age = -18;

        if (age < 0)
        {
            age = 18;
        }

        try
        {
            Person p = new Person("SwagiWagi", 18);
        }
        catch (AgeException ex)
        {
           System.out.println("This does not look right.");
        }
    }
}

这似乎不对,它是混乱且不清楚的代码。

我应该怎么办?

标签: javaexceptiontry-catch

解决方案


是的,在我看来,抛出和捕获太多异常是很麻烦的。

相反,尝试一种完全不必抛出异常的方法。

Scanner sc = new Scanner(System.in);

int age = sc.nextInt();
while (age < 0) {
    System.out.println("Age entered is less than 0. Please enter again.");
    age = sc.nextInt();
}

Person p = new Person("SwagiWagi", age);

在这种情况下,您将永远有一个积极的年龄。

注意:输入的输入应该是一个数字,否则.nextInt()会抛出异常,这是您必须处理的。


推荐阅读