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












15















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







New contributor




PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





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

    – yaseco
    yesterday






  • 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
    yesterday











  • 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
    23 hours ago


















15















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







New contributor




PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2





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

    – yaseco
    yesterday






  • 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
    yesterday











  • 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
    23 hours ago
















15












15








15


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







New contributor




PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












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







New contributor




PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









PsyApPsyAp

785




785




New contributor




PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






PsyAp is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2





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

    – yaseco
    yesterday






  • 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
    yesterday











  • 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
    23 hours ago
















  • 2





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

    – yaseco
    yesterday






  • 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
    yesterday











  • 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
    23 hours ago










2




2





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

– yaseco
yesterday





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

– yaseco
yesterday




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
yesterday





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

– RealSkeptic
yesterday













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
23 hours ago







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
23 hours ago














4 Answers
4






active

oldest

votes


















24














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
    21 hours ago













  • @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
    20 hours ago



















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
    yesterday






  • 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
    yesterday











  • 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
    yesterday











  • 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
    yesterday



















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








New contributor




IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




























    -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
      });


      }
      });






      PsyAp is a new contributor. Be nice, and check out our Code of Conduct.










      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









      24














      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
        21 hours ago













      • @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
        20 hours ago
















      24














      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
        21 hours ago













      • @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
        20 hours ago














      24












      24








      24







      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 yesterday

























      answered yesterday









      EranEran

      290k37477563




      290k37477563








      • 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
        21 hours ago













      • @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
        20 hours ago














      • 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
        21 hours ago













      • @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
        20 hours ago








      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
      21 hours ago







      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
      21 hours ago















      @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
      20 hours ago





      @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
      20 hours ago













      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
        yesterday






      • 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
        yesterday











      • 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
        yesterday











      • 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
        yesterday
















      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
        yesterday






      • 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
        yesterday











      • 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
        yesterday











      • 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
        yesterday














      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 yesterday









      JB NizetJB Nizet

      546k588921018




      546k588921018








      • 1





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

        – RealSkeptic
        yesterday






      • 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
        yesterday











      • 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
        yesterday











      • 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
        yesterday














      • 1





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

        – RealSkeptic
        yesterday






      • 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
        yesterday











      • 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
        yesterday











      • 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
        yesterday








      1




      1





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

      – RealSkeptic
      yesterday





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

      – RealSkeptic
      yesterday




      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
      yesterday





      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
      yesterday













      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
      yesterday





      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
      yesterday













      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
      yesterday





      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
      yesterday











      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








      New contributor




      IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.

























        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








        New contributor




        IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.























          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








          New contributor




          IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.










          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








          New contributor




          IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer






          New contributor




          IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered yesterday









          IvanMIvanM

          192




          192




          New contributor




          IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          IvanM is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.























              -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 yesterday









                  Harsimran17Harsimran17

                  92




                  92






















                      PsyAp is a new contributor. Be nice, and check out our Code of Conduct.










                      draft saved

                      draft discarded


















                      PsyAp is a new contributor. Be nice, and check out our Code of Conduct.













                      PsyAp is a new contributor. Be nice, and check out our Code of Conduct.












                      PsyAp is a new contributor. Be nice, and check out our Code of Conduct.
















                      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