Should i catch all the exception which are thrown

2020-05-03 09:44发布

问题:

try{
   output.format("%d %s %s %.2f%n", input.nextInt(),
        input.next(),input.next(),input.nextDouble());
} catch(FormatterClosedException formatterClosedException){
    System.err.println("Error writing to file. Terminating.");
    break;
} catch(NoSuchElementException noSuchElementException){
    System.err.println("Invalid input. Please try again.");
    input.nextLine();
}

The method format(String format, Object... args) in Formatter class throws two exception: IllegalFormatException and FormatterClosedException but in my book the above code catches NoSuchElementException and FormatterClosedException.

  1. Why did the code catch NoSuchElementException but did not catch IllegalFormatException?
  2. How can we know if we need to catch NoSuchElementException if it is not even stated in the Formatter class format() method in the online documentation ?

回答1:

Document: java.util.NoSuchElementException is a RuntimeException which can be thrown by different classes in Java like Iterator, Enumerator, Scanner or StringTokenizer.

In your case it is Scanner. Its not from format method.

It's just to be in the safer side(if next input is not given then throw this exception).

Sample code which shows the demo

public class NoSuchElementExceptionDemo{
    public static void main(String args[]) {
        Hashtable sampleMap = new Hashtable();
        Enumeration enumeration = sampleMap.elements();
        enumeration.nextElement();  //java.util.NoSuchElementExcepiton here because enumeration is empty
    }
}

Output:
Exception in thread "main" java.util.NoSuchElementException: Hashtable Enumerator
        at java.util.Hashtable$EmptyEnumerator.nextElement(Hashtable.java:1084)
        at test.ExceptionTest.main(NoSuchElementExceptionDemo.java:23)


回答2:

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


回答3:

add another catch with Exception class. That is the parent class.

catch(Exception e){
//your message or
     System.out.print(e.getMessage());
}

You can add catch for every exception that your code throws and in the end add this catch with this Exception parent class. If your exception is not caught by any of the catch then this will caught your exception.

It will catch all exceptions that is raised by your program.