首页 \ 问答 \ Java中抛出异常的顺序(Order of throws exceptions in Java)

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
更新时间:2023-07-27 18:07

最满意答案

这个javadocs说:

OffsetDateTime ,“ ZonedDateTime和“ Instant都将时间线上的瞬间存储为ZonedDateTime级的精度, Instant是最简单的,仅代表瞬间, OffsetDateTime将添加到UTC /格林威治的距离,这允许本地日期时间为ZonedDateTime添加了全时区规则。“

资料来源: https : //docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html

因此, OffsetDateTimeZonedDateTime之间的区别在于后者包括涵盖夏令时调整的规则。

在将数据写入日期时应使用OffsetDateTime,但是我不明白为什么。

一个原因是当地时间抵消的时间总是与时间相同,因此有一个稳定的排序。 相比之下,正面对相应时区规则的调整,具有全时区信息的日期的含义是不稳定的。 (这些确实发生...)

如果(例如)在字段上创建日期的数据库索引,则其含义/排序不稳定的日期是有问题的。


Q: What's the difference between java 8 ZonedDateTime and OffsetDateTime?

The javadocs say this:

"OffsetDateTime, ZonedDateTime and Instant 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 and ZonedDateTime 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. The ZonedDateTime 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.

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。