Should i catch all the exception which are thrown by a method?

前端 未结 3 1362
天涯浪人
天涯浪人 2021-01-27 09:57
try{
   output.format(\"%d %s %s %.2f%n\", input.nextInt(),
        input.next(),input.next(),input.nextDouble());
} catch(FormatterClosedException formatterClosedExcept         


        
3条回答
  •  北海茫月
    2021-01-27 10:23

    In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.

    try{
        //some code
    } catch (FormatterClosedException e1) {
        e.printStackTrace()     //very important - handles the Exception but prints the information!
    } catch (NoSuchElementException e2) {
        e.printStackTrace();
    }
    

    or using the fact, that they all extend Exception:

    try {
        //somecode
    } catch (Exception e) {
        e.printStackTrace;
    };
    

    or since Java 7:

    try {
        //somecode
    } catch (FormatterClosedException | NoSuchElementExceptione) {
        e.printStackTrace;
    };
    

    You have to catch all checked exceptions. It's due to the language grammar. On the other hand, there are unchecked exceptions which doesn't necessarily need to be caught.

    IllegalArgumentException is unchecked exception and therefor doesn't need to be caught. NoSuchInputException can be thrown by input.next(). That's why it's declared to be caught.

    So:

    1. you're dealing with 3 different Exceptions.
    2. They all are unchecked so don't have to be caught.
    3. input.next() can throw NoSuchElementException
    4. format can throw FormatterClosedException

提交回复
热议问题