java - 我应该如何处理构造函数抛出的异常
问题描述
我遇到过这个问题:
我正在制作一个对象,比如说,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.");
}
}
}
这似乎不对,它是混乱且不清楚的代码。
我应该怎么办?
解决方案
是的,在我看来,抛出和捕获太多异常是很麻烦的。
相反,尝试一种完全不必抛出异常的方法。
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()
会抛出异常,这是您必须处理的。
推荐阅读
- c# - 如何使selenium打开https页面,手动显示而自动运行时不显示?
- if-statement - How to get a total number of occurrences in an IF statement
- powershell - Trailing spaces during integer to string conversion in power shell script
- kubernetes - Hybrid between replicaset and daemonset
- javascript - Is it possible to change domparser element to string?
- three.js - Update texture with three.js
- javascript - 页面刷新时 Vue SPA 中的 Auth0 客户端为空
- sql - 使用 SQL 访问数组中 JSON 对象中的键、值
- python - 在 windows 10 中安装虚拟环境
- python-3.x - 如何在不同的数据帧上生成交叉验证以进行监督分类?