Java中抛出异常的顺序(Order of throws exceptions in Java)
我正在编写用于将文件读入Java的代码。
我有一个主要的方法,抛出三个异常。 我想知道如果我在
public static void main(String[] args)
的同一行中切换写异常的顺序会有什么影响。public class SwitchTester { private static Scanner pathInput; public static void main(String[] args) throws IOException, NoSuchElementException, IllegalStateException{
我使用main方法中的代码。 我使用的异常顺序是此代码中的IOException,NoSuchElementException,IllegalStateException。 在主线保持相同的顺序是否重要? 保持在主线上的投掷是否重要?
try{ pathInput = new Scanner(path); }catch(IOException ioException){ System.err.println("Error opening file. Terminating."); System.exit(1); } System.out.printf("%-10s%-15s%-15s%10s%n", "Port", "Destination", "Source", "Data-type"); //readRecords try{ while(pathInput.hasNext()){ //while there is more to read, display record contents System.out.printf("%-10s%-15s%-15s%10s%n", pathInput.next(), pathInput.next(), pathInput.next(), pathInput.next()); } }catch(NoSuchElementException elementException){ System.err.println("File improperly formed. Terminating."); }catch(IllegalStateException stateException){ System.err.println("Error reading from file. Terminating."); }
我很感激你的回答! 谢谢!
I am writing code for reading files into Java.
I have a main method that throws three Exceptions. I am wondering what would the impact would be if I switched the order of writing the exceptions in the same line of
public static void main(String[] args)
.public class SwitchTester { private static Scanner pathInput; public static void main(String[] args) throws IOException, NoSuchElementException, IllegalStateException{
I use the code inside the main method. The order of exceptions I use is IOException, NoSuchElementException, IllegalStateException in this code. Would it matter to keep the same order in the main line? Would it matter to keep throws in the main line or not at all?
try{ pathInput = new Scanner(path); }catch(IOException ioException){ System.err.println("Error opening file. Terminating."); System.exit(1); } System.out.printf("%-10s%-15s%-15s%10s%n", "Port", "Destination", "Source", "Data-type"); //readRecords try{ while(pathInput.hasNext()){ //while there is more to read, display record contents System.out.printf("%-10s%-15s%-15s%10s%n", pathInput.next(), pathInput.next(), pathInput.next(), pathInput.next()); } }catch(NoSuchElementException elementException){ System.err.println("File improperly formed. Terminating."); }catch(IllegalStateException stateException){ System.err.println("Error reading from file. Terminating."); }
I would appreciate your answer! Thanks!
原文:https://stackoverflow.com/questions/35071533
最满意答案
这个javadocs说:
“
OffsetDateTime
,“ZonedDateTime
和“Instant
都将时间线上的瞬间存储为ZonedDateTime
级的精度,Instant
是最简单的,仅代表瞬间,OffsetDateTime
将添加到UTC /格林威治的距离,这允许本地日期时间为ZonedDateTime
添加了全时区规则。“资料来源: https : //docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html
因此,
OffsetDateTime
和ZonedDateTime
之间的区别在于后者包括涵盖夏令时调整的规则。在将数据写入日期时应使用OffsetDateTime,但是我不明白为什么。
一个原因是当地时间抵消的时间总是与时间相同,因此有一个稳定的排序。 相比之下,正面对相应时区规则的调整,具有全时区信息的日期的含义是不稳定的。 (这些确实发生...)
如果(例如)在字段上创建日期的数据库索引,则其含义/排序不稳定的日期是有问题的。
Q: What's the difference between java 8 ZonedDateTime and OffsetDateTime?
The javadocs say this:
"
OffsetDateTime
,ZonedDateTime
andInstant
all store an instant on the time-line to nanosecond precision.Instant
is the simplest, simply representing the instant.OffsetDateTime
adds to the instant the offset from UTC/Greenwich, which allows the local date-time to be obtained.ZonedDateTime
adds full time-zone rules."Source: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html
Thus the difference between
OffsetDateTime
andZonedDateTime
is that the latter includes the rules that cover daylight saving time adjustments and various other anomalies.Stated simply:
Time Zone = ( Offset-From-UTC + Rules-For-Anomalies )
Q: According to documentation
OffsetDateTime
should be used when writing date to database, but I don't get why.Dates with local time offsets always represent the same instants in time, and therefore have a stable ordering. By contrast, the meaning of dates with full timezone information is unstable in the face of adjustments to the rules for the respective timezones. (And these do happen; e.g. for date-time values in the future.) So if you store and then retrieve a
ZonedDateTime
the implementation has a problem:
It can store the computed offset ... and the retrieved object may then have an offset that is inconsistent with the current rules for the zone-id.
It can discard the computed offset ... and the retrieved object then represents a different point in the absolute / universal timeline than the one that was stored.
If you use Java object serialization, the Java 9 implementation takes the first approach. This is arguably the "more correct" way to handle this, but this doesn't appear to be documented. (JDBC drivers and ORM bindings are presumably making similar decisions, and are hopefully getting it right.)
But if you are writing an application that manually stores date/time values, or that rely on
java.sql.DateTime
, then dealing with the complications of a zone-id is ... probably something to be avoided. Hence the advice.Note that dates whose meaning / ordering is unstable over time may be problematic for an application. And since changes to zone rules are an edge case, the problems are liable to emerge at unexpected times.
A (possible) second reason for the advice is that the construction of a
ZonedDateTime
is ambiguous at the certain points. For example in the period in time when you are "putting the clocks back", combining a local time and a zone-id can give you two different offsets. TheZonedDateTime
will consistently pick one over the other ... but this isn't always the correct choice.Now, this could be a problem for any applications that construct
ZonedDateTime
values that way. But from the perspective of someone building an enterprise application is a bigger problem when the (possibly incorrect)ZonedDateTime
values are persistent and used later.
相关问答
更多-
Java 8日期时间:从ZonedDateTime获取一天的开始时间(Java 8 date-time: get start of day from ZonedDateTime)[2023-02-16]
为了更正而更新: 在大多数情况下是相同的 ,请参阅下面的巴西从冬季切换到夏季时的示例: ZonedDateTime zdt = ZonedDateTime.of(2015, 10, 18, 0, 30, 0, 0, ZoneId.of("America/Sao_Paulo")); // switch to summer time ZonedDateTime zdt1 = zdt.truncatedTo(ChronoUnit.DAYS); ZonedDateTime zdt2 = zdt.to ... -
OffsetDateTime表示具有偏移的日期时间,例如。 2007-12-03T10:15:30 + 01:00 您尝试解析的文本不符合OffsetDateTime.的要求OffsetDateTime. 请参阅https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html 被解析的字符串既不包含ZoneOffset也不包含时间。 从字符串和格式化程序的模式,看起来你只需要一个LocalDate。 所以,你可以使用: Local ...
-
请参阅DateTimeUtils ,它处理添加到诸如java.util.Date类的方法: http : //www.threeten.org/threetenbp/apidocs/org/threeten/bp/DateTimeUtils.html See DateTimeUtils which handles the methods added to classes like java.util.Date: http://www.threeten.org/threetenbp/apidocs/org/t ...
-
这将是一种执行转换并确保使用UTC的方法。 我认为这比使用纪元秒提出的解决方案要简洁一些。 Timestamp test = Timestamp.valueOf(entityValue.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime()); This would be a way to do the conversion and ensure UTC is used. That I think is a little cleaner than solut ...
-
这个javadocs说: “ OffsetDateTime ,“ ZonedDateTime和“ Instant都将时间线上的瞬间存储为ZonedDateTime级的精度, Instant是最简单的,仅代表瞬间, OffsetDateTime将添加到UTC /格林威治的距离,这允许本地日期时间为ZonedDateTime添加了全时区规则。“ 资料来源: https : //docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html 因此, ...
-
您可以: 创建一个实现JsonDeserializer
的类型适配器,并将JSON文字转换为您想要的任何ThreeTen类型。 LocalDate示例: @Override public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { if (typeOfT == LocalDate ... -
好吧,你想创建一个ZonedDateTime ,它始终引用一个时区,但你的输入不包含这样的信息,如果输入缺少一个区域,你也没有指示格式化程序使用默认时区。 您的问题有两种解决方案: 指示您的解析器使用时区(此处使用系统tz作为示例) : String oraceDt = "1970-01-01 00:00:00.0"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); ZonedDateTi ...
-
OffsetDateTime解析(OffsetDateTime parsing)[2023-10-20]
OffsetDateTime.parse需要包含偏移量( +/-hh:mm )的字符串, "2011-12-03T10:15:30"不包含该偏移量。 使用LocalDateTime.parse解析并使用OffsetDateTime.of转换结果。 OffsetDateTime.parse requires a string containing an offset (+/-hh:mm), which "2011-12-03T10:15:30" doesn't have. Parse it with Loca ... -
如果您的意思是今天在默认时区: return zonedDateTime.toLocalDate().equals(LocalDate.now()); //you may want to clarify your intent by explicitly setting the time zone: return zonedDateTime.toLocalDate().equals(LocalDate.now(ZoneId.systemDefault())); 如果你的意思是今天与ZonedDateTi ...
-
ZonedDateTime考虑了夏令时。 这与LocalDateTime有所不同。 好吧,那个和时区信息。 ZonedDateTime takes daylight savings into account. That's what differs it from LocalDateTime. Well, that and timezone information.