Why does the compiler allow throws when the method will never throw the Exception Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!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?

Why did Israel vote against lifting the American embargo on Cuba?

Why do C and C++ allow the expression (int) + 4*5?

Can this water damage be explained by lack of gutters and grading issues?

What came first? Venom as the movie or as the song?

How to make an animal which can only breed for a certain number of generations?

Are Flameskulls resistant to magical piercing damage?

Protagonist's race is hidden - should I reveal it?

Is "ein Herz wie das meine" an antiquated or colloquial use of the possesive pronoun?

Is Bran literally the world's memory?

What is the evidence that custom checks in Northern Ireland are going to result in violence?

tabularx column has extra padding at right?

Marquee sign letters

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

Can I ask an author to send me his ebook?

Salesforce - multiple pre production environments

Why does BitLocker not use RSA?

"Destructive force" carried by a B-52?

What documents does someone with a long-term visa need to travel to another Schengen country?

A German immigrant ancestor has a "Registration Affidavit of Alien Enemy" on file. What does that mean exactly?

How do I deal with an erroneously large refund?

How to charge percentage of transaction cost?

false 'Security alert' from Google - every login generates mails from 'no-reply@accounts.google.com'

Kepler's 3rd law: ratios don't fit data

What helicopter has the most rotor blades?



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



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!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 height:90px;width:728px;box-sizing:border-box;








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




935







  • 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

      293k37485565




      293k37485565







      • 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

      550k618981025




      550k618981025







      • 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




          875





















              -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




                  92



























                      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

                      He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

                      Bunad

                      Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum