What happens if a method throws an exception that was not specified in the method declaration with “throws”

前端 未结 6 1296
忘掉有多难
忘掉有多难 2021-01-01 11:27

I\'ve never used the \"throws\" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I\'ve been u

相关标签:
6条回答
  • 2021-01-01 12:07

    The throws key word is used to throw an exception to another method.

    It eases the handle exception to the user. Because then all of the exceptions can be handled in a method which is used to run.

    Mostly it is mainly a method, so that the user does not need to explore inside the method.

    It also throws keyword force to the compiler to handle the exception which could be occurring.

    If you were a API developer, when you write a code, you might see that an exception could occur, so you use the throws keyword to handle it when the method runs.

    0 讨论(0)
  • 2021-01-01 12:12
    1. You need to declare checked exceptions that your method throws.
    2. If you declare 'throws Exception' that pretty much covers most if not all checked exceptions
    3. You can always throw an unchecked runtime exception and not have to declare.

    Im pretty sure if you try to throw a checked exception, and haven't declared the method as throwing that type, the code wont even compile (checking now).

    EDIT, right so if you try something simple like

    public static void main(String[] args) {
       throw new Exception("bad");
    }
    

    you get a compile error.

    Specifically for your question, if you invoke a method that is declared to throw Exception(s) you must either try/catch the method invocation, or declare that your method throws the exceptions.

    0 讨论(0)
  • 2021-01-01 12:13

    If a method is declared with the throws keyword then any other method that wishes to call that method must either be prepared to catch it or declare that itself will throw an exception.

    For instance if you want to pause the application you must call Thread.sleep(milliseconds);

    But the declaration for this method says that it will throw an InterruptedException

    Declaration:

    public static void sleep(long millis) throws InterruptedException
    

    So if you wish to call it for instance in your main method you must either catch it:

    public static void main(String args[]) {
        try {
            Thread.sleep(1000);
        } catch(InterruptedException ie) {
            System.out.println("Opps!");
        }
    }
    

    Or make the method also declare that it is throwing an exception:

    public static void main(String args[]) throws InterruptedException {
        Thread.sleep(1000);
    }
    
    0 讨论(0)
  • 2021-01-01 12:13

    Java throws keyword,

    • Java throws keyword is used to declare an exception.
    • throws is followed by class.
    • Checked exception can be propagated with throws.
    • It provides information to the caller of the method about the exception.

    throws example,

    void m()throws ArithmeticException{  
        //method code  
    }  
    
    0 讨论(0)
  • 2021-01-01 12:22

    It can happen, even with checked exceptions. And sometimes it can break logging.

    Suppose a library method uses this trick to allow an implementation of Runnable that can throw IOException:

    class SneakyThrowTask implements Runnable {
    
        public void run() {
            throwSneakily(new IOException());
        }
    
        private static RuntimeException throwSneakily(Throwable ex) {
            return unsafeCastAndRethrow(ex);
        }
    
        @SuppressWarnings("unchecked")
        private static <X extends Throwable>X unsafeCastAndRethrow(Throwable ex) throws X {
            throw (X) ex;
        }
    
    }
    

    And you call it like this:

    public static void main(String[] args) {
        try {
            new SneakyThrowTask().run();
        } catch (RuntimeException ex) {
            LOGGER.log(ex);
        }
    }
    

    The exception will never be logged. And because it's a checked exception you cannot write this:

    public static void main(String[] args) {
        try {
            new SneakyThrowTask().run();
        } catch (RuntimeException ex) {
            LOGGER.log(ex);
        } catch (IOException ex) {
            LOGGER.log(ex); // Error: unreachable code
        }
    }
    
    0 讨论(0)
  • 2021-01-01 12:29

    Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.

    Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.

    Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.

    Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.

    0 讨论(0)
提交回复
热议问题