Why does the compiler allow throws when the method will never throw the ExceptionHow slow are Java exceptions?The case against checked exceptionsWhy does Java have transient fields?Java: How to throw an Exception to the method caller inside a try catch body?Why does this code using random strings print “hello world”?Missing return statement in a non-void method compilesWhy does the Java compiler allow exceptions to be listed in the throws section that it is impossible for the method to throwWhy is “final” not allowed in Java 8 interface methods?Why is executing Java code in comments with certain Unicode characters allowed?Why is catching checked exceptions allowed for code that does not throw exceptions?

The Target Principal Name Is Incorrect. Cannot Generate SSPI Context (SQL or AD Issue)?

Would it be a copyright violation if I made a character’s full name refer to a song?

How would modern naval warfare have to have developed differently for battleships to still be relevant in the 21st century?

Cascading Repair Costs following Blown Head Gasket on a 2004 Subaru Outback

If the world have massive single giant world tree can it stop earthquake?

Why do some games show lights shine thorugh walls?

Did Karl Marx ever use any example that involved cotton and dollars to illustrate the way capital and surplus value were generated?

Links to webpages in books

A STL-like vector implementation in C++

Is there a maximum distance from a planet that a moon can orbit?

How do I respond to requests for a "guarantee" not to leave after a few months?

Why do some professors with PhDs leave their professorships to teach high school?

Inverse-quotes-quine

How to split an equation in two lines?

Require advice on power conservation for backpacking trip

Computing a trigonometric integral

How can I politely work my way around not liking coffee or beer when it comes to professional networking?

Does squid ink pasta bleed?

Archery in modern conflicts

If I wouldn't want to read the story, is writing it still a good idea?

Graphical representation of connection of people

How risky is real estate?

Is it damaging to turn off a small fridge for two days every week?

Sci fi short story, robot city that nags people about health



Why does the compiler allow throws when the method will never throw the Exception


How slow are Java exceptions?The case against checked exceptionsWhy does Java have transient fields?Java: How to throw an Exception to the method caller inside a try catch body?Why does this code using random strings print “hello world”?Missing return statement in a non-void method compilesWhy does the Java compiler allow exceptions to be listed in the throws section that it is impossible for the method to throwWhy is “final” not allowed in Java 8 interface methods?Why is executing Java code in comments with certain Unicode characters allowed?Why is catching checked exceptions allowed for code that does not throw exceptions?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








18















I am wondering why the java compiler allows throws in the method declaration when the method will never throw the Exception. Because "throws" is a way of handling the exception (telling the caller to handle it).



Since there are two ways of handling exception (throws & try/catch). In a try/catch, it doesn't allow the catch of an exception not thrown in the try block but it allows a throws in a method that does may not throw the exception.



private static void methodA() 
try
// Do something
// No IO operation here
catch (IOException ex) //This line does not compile because
//exception is never thrown from try
// Handle



private static void methodB() throws IOException //Why does this //compile when excetion is never thrown in function body
//Do Something
//No IO operation










share|improve this question

















  • 2





    TLDR: it's a design choice, and there isn't right or wrong here.

    – yaseco
    Mar 25 at 9:44






  • 1





    As we are not the designers of the language, "why" questions would be hard to answer with anything but speculative, opinion-based answers.

    – RealSkeptic
    Mar 25 at 9:45











  • I also find the term throws to be misleading. I parse it as could_throw in my mind now and it seems to fit better with its behaviour.

    – Eric Duminil
    Mar 25 at 15:54


















18















I am wondering why the java compiler allows throws in the method declaration when the method will never throw the Exception. Because "throws" is a way of handling the exception (telling the caller to handle it).



Since there are two ways of handling exception (throws & try/catch). In a try/catch, it doesn't allow the catch of an exception not thrown in the try block but it allows a throws in a method that does may not throw the exception.



private static void methodA() 
try
// Do something
// No IO operation here
catch (IOException ex) //This line does not compile because
//exception is never thrown from try
// Handle



private static void methodB() throws IOException //Why does this //compile when excetion is never thrown in function body
//Do Something
//No IO operation










share|improve this question

















  • 2





    TLDR: it's a design choice, and there isn't right or wrong here.

    – yaseco
    Mar 25 at 9:44






  • 1





    As we are not the designers of the language, "why" questions would be hard to answer with anything but speculative, opinion-based answers.

    – RealSkeptic
    Mar 25 at 9:45











  • I also find the term throws to be misleading. I parse it as could_throw in my mind now and it seems to fit better with its behaviour.

    – Eric Duminil
    Mar 25 at 15:54














18












18








18


1






I am wondering why the java compiler allows throws in the method declaration when the method will never throw the Exception. Because "throws" is a way of handling the exception (telling the caller to handle it).



Since there are two ways of handling exception (throws & try/catch). In a try/catch, it doesn't allow the catch of an exception not thrown in the try block but it allows a throws in a method that does may not throw the exception.



private static void methodA() 
try
// Do something
// No IO operation here
catch (IOException ex) //This line does not compile because
//exception is never thrown from try
// Handle



private static void methodB() throws IOException //Why does this //compile when excetion is never thrown in function body
//Do Something
//No IO operation










share|improve this question














I am wondering why the java compiler allows throws in the method declaration when the method will never throw the Exception. Because "throws" is a way of handling the exception (telling the caller to handle it).



Since there are two ways of handling exception (throws & try/catch). In a try/catch, it doesn't allow the catch of an exception not thrown in the try block but it allows a throws in a method that does may not throw the exception.



private static void methodA() 
try
// Do something
// No IO operation here
catch (IOException ex) //This line does not compile because
//exception is never thrown from try
// Handle



private static void methodB() throws IOException //Why does this //compile when excetion is never thrown in function body
//Do Something
//No IO operation







java checked-exceptions






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 9:38









PsyApPsyAp

935 bronze badges




935 bronze badges







  • 2





    TLDR: it's a design choice, and there isn't right or wrong here.

    – yaseco
    Mar 25 at 9:44






  • 1





    As we are not the designers of the language, "why" questions would be hard to answer with anything but speculative, opinion-based answers.

    – RealSkeptic
    Mar 25 at 9:45











  • I also find the term throws to be misleading. I parse it as could_throw in my mind now and it seems to fit better with its behaviour.

    – Eric Duminil
    Mar 25 at 15:54













  • 2





    TLDR: it's a design choice, and there isn't right or wrong here.

    – yaseco
    Mar 25 at 9:44






  • 1





    As we are not the designers of the language, "why" questions would be hard to answer with anything but speculative, opinion-based answers.

    – RealSkeptic
    Mar 25 at 9:45











  • I also find the term throws to be misleading. I parse it as could_throw in my mind now and it seems to fit better with its behaviour.

    – Eric Duminil
    Mar 25 at 15:54








2




2





TLDR: it's a design choice, and there isn't right or wrong here.

– yaseco
Mar 25 at 9:44





TLDR: it's a design choice, and there isn't right or wrong here.

– yaseco
Mar 25 at 9:44




1




1





As we are not the designers of the language, "why" questions would be hard to answer with anything but speculative, opinion-based answers.

– RealSkeptic
Mar 25 at 9:45





As we are not the designers of the language, "why" questions would be hard to answer with anything but speculative, opinion-based answers.

– RealSkeptic
Mar 25 at 9:45













I also find the term throws to be misleading. I parse it as could_throw in my mind now and it seems to fit better with its behaviour.

– Eric Duminil
Mar 25 at 15:54






I also find the term throws to be misleading. I parse it as could_throw in my mind now and it seems to fit better with its behaviour.

– Eric Duminil
Mar 25 at 15:54













4 Answers
4






active

oldest

votes


















25














The throws clause is part of the method's contract. It requires the caller of the method to behave as if the specified exception may be thrown by the method (i.e. either catch the exception or declare their own throws clause).



It's possible that the initial version of a method does not throw the exception specified in the throws clause, but a future version can throw it without breaking the API (i.e. any existing code that calls the method will still pass compilation).



The opposite it also possible. If the method used to throw the exception specified in the throws clause, but a future version of it doesn't throw it anymore, you should keep the throws clause in order not to break existing code that uses your method.



First example:



Suppose you have this code which uses methodB:



private static void methodA() 
methodB(); // doesn't have throws IOException clause yet



If later you want to change methodB to throw IOException, methodA will stop passing compilation.



Second example:



Suppose you have this code which uses methodB:



private static void methodA() 
try
methodB(); // throws IOException

catch (IOException ex)





If you remove the throws clause from a future version of methodB, methodA won't pass compilation anymore.



This example is not very interesting when methodA is private, because it can only be used locally (within the same class, where it's easy to modify all the methods that call it).



However, if it becomes public, you don't know who uses (or will use) your method, so you have no control of all the code that may break as a result of adding or removing the throws clause.



And if it's an instance method, there's another reason for allowing the throws clause even if you don't throw the exception - the method can be overridden, and the overriding method may throw the exception even if the base class implementation does not.






share|improve this answer




















  • 2





    The last point about the override should be given more emphasis, IMHO. The notion of "what if functions change" is less concrete than the notion of "even though the parent function would have no reason to throw a particular exceptions, even today's versions of child functions might need to do so.

    – supercat
    Mar 25 at 17:47












  • @supercat agreed, but the code in the question has static methods, which cannot be overridden, which is why most my answer gives reasons that apply to static methods.

    – Eran
    Mar 25 at 19:42


















8














Because the signature defines the contract of the method. Even if the method doesn't throw an IOException now, maybe it will in the future, and you want to prepare for that possibility.



Suppose you just provide a dummy implementation for the method for now, but you know that, later, the actual implementation will potentially throw an IOException.
If the compiler prevented you from adding this throws clause, you would be forced to rework all the calls (recursively) to that method once you provide the actual implementation of the method.






share|improve this answer


















  • 1





    It's debatable whether a private method can be said to have a contract.

    – RealSkeptic
    Mar 25 at 9:44






  • 1





    It defines a contract for all the other methods in the class. And these methods might, in turn,want to declare an IOException because they rely on the contract of the private method they call.

    – JB Nizet
    Mar 25 at 9:47











  • You can also decide to change the return value of a private method. That's also part of the "contract", isn't it? And yet, what you do when that happens is fix the code that calls it. The same could have been done with "throws".

    – RealSkeptic
    Mar 25 at 9:49











  • I don't see how that relates to the question, which is: why does the compiler allow to have a throws clause for an exception that is not thrown by the method. What's your point? The compiler also allows you to use long as the return type even if you only ever return constant values that fit into an int. Why? For the same reason: you define the contract, which is that the method may, now or later, return a long value.

    – JB Nizet
    Mar 25 at 9:54


















0














Keyword throws tells programmer that there could be an IOException happening in the method. Now if you didn't specify try/catch it means that when exception is thrown program will stop working, while in try/catch you handle it by doing something else if thrown exception.



Use throws for readability and specifying the possibility of exception and use try/catch to tell program what to do in case of exception.






share|improve this answer






























    -1















    1. The methodB throws IOException, so the method calling methodB is responsible for catching the exception which will be thrown by methodB. Try calling methodB from other methods, it will ask you to catch it or re-throw the IOException. Somewhere you will have to catch the IOException in the chain (in try/catch block). So you wont get compile time error.



      private void sampleMethod()
      try
      methodB();
      catch (IOException e)
      // TODO Auto-generated catch block
      e.printStackTrace();



    2. try/catch in methodA admittedly swallows the exception, that means methodA is responsible for catching the exception in try/catch block.
      "Every statement in any java program must be reachable i.e every statement must be executable at least once"
      So, you will get compiler error as your try block doesn't have any code to cause IOException.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55334879%2fwhy-does-the-compiler-allow-throws-when-the-method-will-never-throw-the-exceptio%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      25














      The throws clause is part of the method's contract. It requires the caller of the method to behave as if the specified exception may be thrown by the method (i.e. either catch the exception or declare their own throws clause).



      It's possible that the initial version of a method does not throw the exception specified in the throws clause, but a future version can throw it without breaking the API (i.e. any existing code that calls the method will still pass compilation).



      The opposite it also possible. If the method used to throw the exception specified in the throws clause, but a future version of it doesn't throw it anymore, you should keep the throws clause in order not to break existing code that uses your method.



      First example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      methodB(); // doesn't have throws IOException clause yet



      If later you want to change methodB to throw IOException, methodA will stop passing compilation.



      Second example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      try
      methodB(); // throws IOException

      catch (IOException ex)





      If you remove the throws clause from a future version of methodB, methodA won't pass compilation anymore.



      This example is not very interesting when methodA is private, because it can only be used locally (within the same class, where it's easy to modify all the methods that call it).



      However, if it becomes public, you don't know who uses (or will use) your method, so you have no control of all the code that may break as a result of adding or removing the throws clause.



      And if it's an instance method, there's another reason for allowing the throws clause even if you don't throw the exception - the method can be overridden, and the overriding method may throw the exception even if the base class implementation does not.






      share|improve this answer




















      • 2





        The last point about the override should be given more emphasis, IMHO. The notion of "what if functions change" is less concrete than the notion of "even though the parent function would have no reason to throw a particular exceptions, even today's versions of child functions might need to do so.

        – supercat
        Mar 25 at 17:47












      • @supercat agreed, but the code in the question has static methods, which cannot be overridden, which is why most my answer gives reasons that apply to static methods.

        – Eran
        Mar 25 at 19:42















      25














      The throws clause is part of the method's contract. It requires the caller of the method to behave as if the specified exception may be thrown by the method (i.e. either catch the exception or declare their own throws clause).



      It's possible that the initial version of a method does not throw the exception specified in the throws clause, but a future version can throw it without breaking the API (i.e. any existing code that calls the method will still pass compilation).



      The opposite it also possible. If the method used to throw the exception specified in the throws clause, but a future version of it doesn't throw it anymore, you should keep the throws clause in order not to break existing code that uses your method.



      First example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      methodB(); // doesn't have throws IOException clause yet



      If later you want to change methodB to throw IOException, methodA will stop passing compilation.



      Second example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      try
      methodB(); // throws IOException

      catch (IOException ex)





      If you remove the throws clause from a future version of methodB, methodA won't pass compilation anymore.



      This example is not very interesting when methodA is private, because it can only be used locally (within the same class, where it's easy to modify all the methods that call it).



      However, if it becomes public, you don't know who uses (or will use) your method, so you have no control of all the code that may break as a result of adding or removing the throws clause.



      And if it's an instance method, there's another reason for allowing the throws clause even if you don't throw the exception - the method can be overridden, and the overriding method may throw the exception even if the base class implementation does not.






      share|improve this answer




















      • 2





        The last point about the override should be given more emphasis, IMHO. The notion of "what if functions change" is less concrete than the notion of "even though the parent function would have no reason to throw a particular exceptions, even today's versions of child functions might need to do so.

        – supercat
        Mar 25 at 17:47












      • @supercat agreed, but the code in the question has static methods, which cannot be overridden, which is why most my answer gives reasons that apply to static methods.

        – Eran
        Mar 25 at 19:42













      25












      25








      25







      The throws clause is part of the method's contract. It requires the caller of the method to behave as if the specified exception may be thrown by the method (i.e. either catch the exception or declare their own throws clause).



      It's possible that the initial version of a method does not throw the exception specified in the throws clause, but a future version can throw it without breaking the API (i.e. any existing code that calls the method will still pass compilation).



      The opposite it also possible. If the method used to throw the exception specified in the throws clause, but a future version of it doesn't throw it anymore, you should keep the throws clause in order not to break existing code that uses your method.



      First example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      methodB(); // doesn't have throws IOException clause yet



      If later you want to change methodB to throw IOException, methodA will stop passing compilation.



      Second example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      try
      methodB(); // throws IOException

      catch (IOException ex)





      If you remove the throws clause from a future version of methodB, methodA won't pass compilation anymore.



      This example is not very interesting when methodA is private, because it can only be used locally (within the same class, where it's easy to modify all the methods that call it).



      However, if it becomes public, you don't know who uses (or will use) your method, so you have no control of all the code that may break as a result of adding or removing the throws clause.



      And if it's an instance method, there's another reason for allowing the throws clause even if you don't throw the exception - the method can be overridden, and the overriding method may throw the exception even if the base class implementation does not.






      share|improve this answer















      The throws clause is part of the method's contract. It requires the caller of the method to behave as if the specified exception may be thrown by the method (i.e. either catch the exception or declare their own throws clause).



      It's possible that the initial version of a method does not throw the exception specified in the throws clause, but a future version can throw it without breaking the API (i.e. any existing code that calls the method will still pass compilation).



      The opposite it also possible. If the method used to throw the exception specified in the throws clause, but a future version of it doesn't throw it anymore, you should keep the throws clause in order not to break existing code that uses your method.



      First example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      methodB(); // doesn't have throws IOException clause yet



      If later you want to change methodB to throw IOException, methodA will stop passing compilation.



      Second example:



      Suppose you have this code which uses methodB:



      private static void methodA() 
      try
      methodB(); // throws IOException

      catch (IOException ex)





      If you remove the throws clause from a future version of methodB, methodA won't pass compilation anymore.



      This example is not very interesting when methodA is private, because it can only be used locally (within the same class, where it's easy to modify all the methods that call it).



      However, if it becomes public, you don't know who uses (or will use) your method, so you have no control of all the code that may break as a result of adding or removing the throws clause.



      And if it's an instance method, there's another reason for allowing the throws clause even if you don't throw the exception - the method can be overridden, and the overriding method may throw the exception even if the base class implementation does not.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 25 at 9:53

























      answered Mar 25 at 9:43









      EranEran

      300k39 gold badges509 silver badges584 bronze badges




      300k39 gold badges509 silver badges584 bronze badges







      • 2





        The last point about the override should be given more emphasis, IMHO. The notion of "what if functions change" is less concrete than the notion of "even though the parent function would have no reason to throw a particular exceptions, even today's versions of child functions might need to do so.

        – supercat
        Mar 25 at 17:47












      • @supercat agreed, but the code in the question has static methods, which cannot be overridden, which is why most my answer gives reasons that apply to static methods.

        – Eran
        Mar 25 at 19:42












      • 2





        The last point about the override should be given more emphasis, IMHO. The notion of "what if functions change" is less concrete than the notion of "even though the parent function would have no reason to throw a particular exceptions, even today's versions of child functions might need to do so.

        – supercat
        Mar 25 at 17:47












      • @supercat agreed, but the code in the question has static methods, which cannot be overridden, which is why most my answer gives reasons that apply to static methods.

        – Eran
        Mar 25 at 19:42







      2




      2





      The last point about the override should be given more emphasis, IMHO. The notion of "what if functions change" is less concrete than the notion of "even though the parent function would have no reason to throw a particular exceptions, even today's versions of child functions might need to do so.

      – supercat
      Mar 25 at 17:47






      The last point about the override should be given more emphasis, IMHO. The notion of "what if functions change" is less concrete than the notion of "even though the parent function would have no reason to throw a particular exceptions, even today's versions of child functions might need to do so.

      – supercat
      Mar 25 at 17:47














      @supercat agreed, but the code in the question has static methods, which cannot be overridden, which is why most my answer gives reasons that apply to static methods.

      – Eran
      Mar 25 at 19:42





      @supercat agreed, but the code in the question has static methods, which cannot be overridden, which is why most my answer gives reasons that apply to static methods.

      – Eran
      Mar 25 at 19:42













      8














      Because the signature defines the contract of the method. Even if the method doesn't throw an IOException now, maybe it will in the future, and you want to prepare for that possibility.



      Suppose you just provide a dummy implementation for the method for now, but you know that, later, the actual implementation will potentially throw an IOException.
      If the compiler prevented you from adding this throws clause, you would be forced to rework all the calls (recursively) to that method once you provide the actual implementation of the method.






      share|improve this answer


















      • 1





        It's debatable whether a private method can be said to have a contract.

        – RealSkeptic
        Mar 25 at 9:44






      • 1





        It defines a contract for all the other methods in the class. And these methods might, in turn,want to declare an IOException because they rely on the contract of the private method they call.

        – JB Nizet
        Mar 25 at 9:47











      • You can also decide to change the return value of a private method. That's also part of the "contract", isn't it? And yet, what you do when that happens is fix the code that calls it. The same could have been done with "throws".

        – RealSkeptic
        Mar 25 at 9:49











      • I don't see how that relates to the question, which is: why does the compiler allow to have a throws clause for an exception that is not thrown by the method. What's your point? The compiler also allows you to use long as the return type even if you only ever return constant values that fit into an int. Why? For the same reason: you define the contract, which is that the method may, now or later, return a long value.

        – JB Nizet
        Mar 25 at 9:54















      8














      Because the signature defines the contract of the method. Even if the method doesn't throw an IOException now, maybe it will in the future, and you want to prepare for that possibility.



      Suppose you just provide a dummy implementation for the method for now, but you know that, later, the actual implementation will potentially throw an IOException.
      If the compiler prevented you from adding this throws clause, you would be forced to rework all the calls (recursively) to that method once you provide the actual implementation of the method.






      share|improve this answer


















      • 1





        It's debatable whether a private method can be said to have a contract.

        – RealSkeptic
        Mar 25 at 9:44






      • 1





        It defines a contract for all the other methods in the class. And these methods might, in turn,want to declare an IOException because they rely on the contract of the private method they call.

        – JB Nizet
        Mar 25 at 9:47











      • You can also decide to change the return value of a private method. That's also part of the "contract", isn't it? And yet, what you do when that happens is fix the code that calls it. The same could have been done with "throws".

        – RealSkeptic
        Mar 25 at 9:49











      • I don't see how that relates to the question, which is: why does the compiler allow to have a throws clause for an exception that is not thrown by the method. What's your point? The compiler also allows you to use long as the return type even if you only ever return constant values that fit into an int. Why? For the same reason: you define the contract, which is that the method may, now or later, return a long value.

        – JB Nizet
        Mar 25 at 9:54













      8












      8








      8







      Because the signature defines the contract of the method. Even if the method doesn't throw an IOException now, maybe it will in the future, and you want to prepare for that possibility.



      Suppose you just provide a dummy implementation for the method for now, but you know that, later, the actual implementation will potentially throw an IOException.
      If the compiler prevented you from adding this throws clause, you would be forced to rework all the calls (recursively) to that method once you provide the actual implementation of the method.






      share|improve this answer













      Because the signature defines the contract of the method. Even if the method doesn't throw an IOException now, maybe it will in the future, and you want to prepare for that possibility.



      Suppose you just provide a dummy implementation for the method for now, but you know that, later, the actual implementation will potentially throw an IOException.
      If the compiler prevented you from adding this throws clause, you would be forced to rework all the calls (recursively) to that method once you provide the actual implementation of the method.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 25 at 9:43









      JB NizetJB Nizet

      558k63 gold badges922 silver badges1036 bronze badges




      558k63 gold badges922 silver badges1036 bronze badges







      • 1





        It's debatable whether a private method can be said to have a contract.

        – RealSkeptic
        Mar 25 at 9:44






      • 1





        It defines a contract for all the other methods in the class. And these methods might, in turn,want to declare an IOException because they rely on the contract of the private method they call.

        – JB Nizet
        Mar 25 at 9:47











      • You can also decide to change the return value of a private method. That's also part of the "contract", isn't it? And yet, what you do when that happens is fix the code that calls it. The same could have been done with "throws".

        – RealSkeptic
        Mar 25 at 9:49











      • I don't see how that relates to the question, which is: why does the compiler allow to have a throws clause for an exception that is not thrown by the method. What's your point? The compiler also allows you to use long as the return type even if you only ever return constant values that fit into an int. Why? For the same reason: you define the contract, which is that the method may, now or later, return a long value.

        – JB Nizet
        Mar 25 at 9:54












      • 1





        It's debatable whether a private method can be said to have a contract.

        – RealSkeptic
        Mar 25 at 9:44






      • 1





        It defines a contract for all the other methods in the class. And these methods might, in turn,want to declare an IOException because they rely on the contract of the private method they call.

        – JB Nizet
        Mar 25 at 9:47











      • You can also decide to change the return value of a private method. That's also part of the "contract", isn't it? And yet, what you do when that happens is fix the code that calls it. The same could have been done with "throws".

        – RealSkeptic
        Mar 25 at 9:49











      • I don't see how that relates to the question, which is: why does the compiler allow to have a throws clause for an exception that is not thrown by the method. What's your point? The compiler also allows you to use long as the return type even if you only ever return constant values that fit into an int. Why? For the same reason: you define the contract, which is that the method may, now or later, return a long value.

        – JB Nizet
        Mar 25 at 9:54







      1




      1





      It's debatable whether a private method can be said to have a contract.

      – RealSkeptic
      Mar 25 at 9:44





      It's debatable whether a private method can be said to have a contract.

      – RealSkeptic
      Mar 25 at 9:44




      1




      1





      It defines a contract for all the other methods in the class. And these methods might, in turn,want to declare an IOException because they rely on the contract of the private method they call.

      – JB Nizet
      Mar 25 at 9:47





      It defines a contract for all the other methods in the class. And these methods might, in turn,want to declare an IOException because they rely on the contract of the private method they call.

      – JB Nizet
      Mar 25 at 9:47













      You can also decide to change the return value of a private method. That's also part of the "contract", isn't it? And yet, what you do when that happens is fix the code that calls it. The same could have been done with "throws".

      – RealSkeptic
      Mar 25 at 9:49





      You can also decide to change the return value of a private method. That's also part of the "contract", isn't it? And yet, what you do when that happens is fix the code that calls it. The same could have been done with "throws".

      – RealSkeptic
      Mar 25 at 9:49













      I don't see how that relates to the question, which is: why does the compiler allow to have a throws clause for an exception that is not thrown by the method. What's your point? The compiler also allows you to use long as the return type even if you only ever return constant values that fit into an int. Why? For the same reason: you define the contract, which is that the method may, now or later, return a long value.

      – JB Nizet
      Mar 25 at 9:54





      I don't see how that relates to the question, which is: why does the compiler allow to have a throws clause for an exception that is not thrown by the method. What's your point? The compiler also allows you to use long as the return type even if you only ever return constant values that fit into an int. Why? For the same reason: you define the contract, which is that the method may, now or later, return a long value.

      – JB Nizet
      Mar 25 at 9:54











      0














      Keyword throws tells programmer that there could be an IOException happening in the method. Now if you didn't specify try/catch it means that when exception is thrown program will stop working, while in try/catch you handle it by doing something else if thrown exception.



      Use throws for readability and specifying the possibility of exception and use try/catch to tell program what to do in case of exception.






      share|improve this answer



























        0














        Keyword throws tells programmer that there could be an IOException happening in the method. Now if you didn't specify try/catch it means that when exception is thrown program will stop working, while in try/catch you handle it by doing something else if thrown exception.



        Use throws for readability and specifying the possibility of exception and use try/catch to tell program what to do in case of exception.






        share|improve this answer

























          0












          0








          0







          Keyword throws tells programmer that there could be an IOException happening in the method. Now if you didn't specify try/catch it means that when exception is thrown program will stop working, while in try/catch you handle it by doing something else if thrown exception.



          Use throws for readability and specifying the possibility of exception and use try/catch to tell program what to do in case of exception.






          share|improve this answer













          Keyword throws tells programmer that there could be an IOException happening in the method. Now if you didn't specify try/catch it means that when exception is thrown program will stop working, while in try/catch you handle it by doing something else if thrown exception.



          Use throws for readability and specifying the possibility of exception and use try/catch to tell program what to do in case of exception.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 25 at 9:50









          IvanMIvanM

          875 bronze badges




          875 bronze badges





















              -1















              1. The methodB throws IOException, so the method calling methodB is responsible for catching the exception which will be thrown by methodB. Try calling methodB from other methods, it will ask you to catch it or re-throw the IOException. Somewhere you will have to catch the IOException in the chain (in try/catch block). So you wont get compile time error.



                private void sampleMethod()
                try
                methodB();
                catch (IOException e)
                // TODO Auto-generated catch block
                e.printStackTrace();



              2. try/catch in methodA admittedly swallows the exception, that means methodA is responsible for catching the exception in try/catch block.
                "Every statement in any java program must be reachable i.e every statement must be executable at least once"
                So, you will get compiler error as your try block doesn't have any code to cause IOException.






              share|improve this answer



























                -1















                1. The methodB throws IOException, so the method calling methodB is responsible for catching the exception which will be thrown by methodB. Try calling methodB from other methods, it will ask you to catch it or re-throw the IOException. Somewhere you will have to catch the IOException in the chain (in try/catch block). So you wont get compile time error.



                  private void sampleMethod()
                  try
                  methodB();
                  catch (IOException e)
                  // TODO Auto-generated catch block
                  e.printStackTrace();



                2. try/catch in methodA admittedly swallows the exception, that means methodA is responsible for catching the exception in try/catch block.
                  "Every statement in any java program must be reachable i.e every statement must be executable at least once"
                  So, you will get compiler error as your try block doesn't have any code to cause IOException.






                share|improve this answer

























                  -1












                  -1








                  -1








                  1. The methodB throws IOException, so the method calling methodB is responsible for catching the exception which will be thrown by methodB. Try calling methodB from other methods, it will ask you to catch it or re-throw the IOException. Somewhere you will have to catch the IOException in the chain (in try/catch block). So you wont get compile time error.



                    private void sampleMethod()
                    try
                    methodB();
                    catch (IOException e)
                    // TODO Auto-generated catch block
                    e.printStackTrace();



                  2. try/catch in methodA admittedly swallows the exception, that means methodA is responsible for catching the exception in try/catch block.
                    "Every statement in any java program must be reachable i.e every statement must be executable at least once"
                    So, you will get compiler error as your try block doesn't have any code to cause IOException.






                  share|improve this answer














                  1. The methodB throws IOException, so the method calling methodB is responsible for catching the exception which will be thrown by methodB. Try calling methodB from other methods, it will ask you to catch it or re-throw the IOException. Somewhere you will have to catch the IOException in the chain (in try/catch block). So you wont get compile time error.



                    private void sampleMethod()
                    try
                    methodB();
                    catch (IOException e)
                    // TODO Auto-generated catch block
                    e.printStackTrace();



                  2. try/catch in methodA admittedly swallows the exception, that means methodA is responsible for catching the exception in try/catch block.
                    "Every statement in any java program must be reachable i.e every statement must be executable at least once"
                    So, you will get compiler error as your try block doesn't have any code to cause IOException.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 25 at 10:49









                  Harsimran17Harsimran17

                  92 bronze badges




                  92 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55334879%2fwhy-does-the-compiler-allow-throws-when-the-method-will-never-throw-the-exceptio%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript