gpt4 book ai didi

java - javax.swing.JFormattedTextField.AbstractFormatter.stringToValue(String) 的具体实现

转载 作者:行者123 更新时间:2023-11-30 06:22:02 24 4
gpt4 key购买 nike

我正在提供具体的实现:

就我而言,我需要处理 java.time.LocalTime ,所以我最初写道:

@Override
public Object stringToValue(String text) throws ParseException {
return LocalTime.parse(text);
}

事实证明,我实际上需要自己转换异常:

@Override
public Object stringToValue(String text) throws ParseException {
try {
return LocalTime.parse(text);
} catch (DateTimeParseException e) {
// API expect a ParseException to report an error in conversion
// need to cast DateTimeParseException into ParseException
throw new ParseException(e.getParsedString(), e.getErrorIndex());
}
}

我想知道是否有更简单的方法可以将 java.time.format.DateTimeParseException 转换为 java.text.ParseException,或者我是否遗漏了一些明显的东西将一个异常转换为另一个异常?

最佳答案

如果我理解这个问题,您也许可以使用 Throwable#initCause(Throwable) 方法。

Throwable#initCause(Throwable) (Java Platform SE 8)

Initializes the cause of this throwable to the specified value. (The cause is the throwable that caused this throwable to get thrown.) This method can be called at most once. It is generally called from within the constructor, or immediately after creating the throwable. If this throwable was created with Throwable(Throwable) or Throwable(String,Throwable), this method cannot be called even once.

@Override
public Object stringToValue(String text) throws ParseException {
try {
return ...;
} catch (DateTimeParseException ex) {
throw (ParseException) new ParseException(
ex.getMessage(), ex.getErrorIndex()).initCause(ex);
}

关于java - javax.swing.JFormattedTextField.AbstractFormatter.stringToValue(String) 的具体实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47921974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com