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

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

                      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

                      Slayer Innehåll Historia | Stil, komposition och lyrik | Bandets betydelse och framgångar | Sidoprojekt och samarbeten | Kontroverser | Medlemmar | Utmärkelser och nomineringar | Turnéer och festivaler | Diskografi | Referenser | Externa länkar | Navigeringsmenywww.slayer.net”Metal Massacre vol. 1””Metal Massacre vol. 3””Metal Massacre Volume III””Show No Mercy””Haunting the Chapel””Live Undead””Hell Awaits””Reign in Blood””Reign in Blood””Gold & Platinum – Reign in Blood””Golden Gods Awards Winners”originalet”Kerrang! Hall Of Fame””Slayer Looks Back On 37-Year Career In New Video Series: Part Two””South of Heaven””Gold & Platinum – South of Heaven””Seasons in the Abyss””Gold & Platinum - Seasons in the Abyss””Divine Intervention””Divine Intervention - Release group by Slayer””Gold & Platinum - Divine Intervention””Live Intrusion””Undisputed Attitude””Abolish Government/Superficial Love””Release “Slatanic Slaughter: A Tribute to Slayer” by Various Artists””Diabolus in Musica””Soundtrack to the Apocalypse””God Hates Us All””Systematic - Relationships””War at the Warfield””Gold & Platinum - War at the Warfield””Soundtrack to the Apocalypse””Gold & Platinum - Still Reigning””Metallica, Slayer, Iron Mauden Among Winners At Metal Hammer Awards””Eternal Pyre””Eternal Pyre - Slayer release group””Eternal Pyre””Metal Storm Awards 2006””Kerrang! Hall Of Fame””Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Bullet-For My Valentine booed at Metal Hammer Golden Gods Awards””Unholy Aliance””The End Of Slayer?””Slayer: We Could Thrash Out Two More Albums If We're Fast Enough...””'The Unholy Alliance: Chapter III' UK Dates Added”originalet”Megadeth And Slayer To Co-Headline 'Canadian Carnage' Trek”originalet”World Painted Blood””Release “World Painted Blood” by Slayer””Metallica Heading To Cinemas””Slayer, Megadeth To Join Forces For 'European Carnage' Tour - Dec. 18, 2010”originalet”Slayer's Hanneman Contracts Acute Infection; Band To Bring In Guest Guitarist””Cannibal Corpse's Pat O'Brien Will Step In As Slayer's Guest Guitarist”originalet”Slayer’s Jeff Hanneman Dead at 49””Dave Lombardo Says He Made Only $67,000 In 2011 While Touring With Slayer””Slayer: We Do Not Agree With Dave Lombardo's Substance Or Timeline Of Events””Slayer Welcomes Drummer Paul Bostaph Back To The Fold””Slayer Hope to Unveil Never-Before-Heard Jeff Hanneman Material on Next Album””Slayer Debut New Song 'Implode' During Surprise Golden Gods Appearance””Release group Repentless by Slayer””Repentless - Slayer - Credits””Slayer””Metal Storm Awards 2015””Slayer - to release comic book "Repentless #1"””Slayer To Release 'Repentless' 6.66" Vinyl Box Set””BREAKING NEWS: Slayer Announce Farewell Tour””Slayer Recruit Lamb of God, Anthrax, Behemoth + Testament for Final Tour””Slayer lägger ner efter 37 år””Slayer Announces Second North American Leg Of 'Final' Tour””Final World Tour””Slayer Announces Final European Tour With Lamb of God, Anthrax And Obituary””Slayer To Tour Europe With Lamb of God, Anthrax And Obituary””Slayer To Play 'Last French Show Ever' At Next Year's Hellfst””Slayer's Final World Tour Will Extend Into 2019””Death Angel's Rob Cavestany On Slayer's 'Farewell' Tour: 'Some Of Us Could See This Coming'””Testament Has No Plans To Retire Anytime Soon, Says Chuck Billy””Anthrax's Scott Ian On Slayer's 'Farewell' Tour Plans: 'I Was Surprised And I Wasn't Surprised'””Slayer””Slayer's Morbid Schlock””Review/Rock; For Slayer, the Mania Is the Message””Slayer - Biography””Slayer - Reign In Blood”originalet”Dave Lombardo””An exclusive oral history of Slayer”originalet”Exclusive! Interview With Slayer Guitarist Jeff Hanneman”originalet”Thinking Out Loud: Slayer's Kerry King on hair metal, Satan and being polite””Slayer Lyrics””Slayer - Biography””Most influential artists for extreme metal music””Slayer - Reign in Blood””Slayer guitarist Jeff Hanneman dies aged 49””Slatanic Slaughter: A Tribute to Slayer””Gateway to Hell: A Tribute to Slayer””Covered In Blood””Slayer: The Origins of Thrash in San Francisco, CA.””Why They Rule - #6 Slayer”originalet”Guitar World's 100 Greatest Heavy Metal Guitarists Of All Time”originalet”The fans have spoken: Slayer comes out on top in readers' polls”originalet”Tribute to Jeff Hanneman (1964-2013)””Lamb Of God Frontman: We Sound Like A Slayer Rip-Off””BEHEMOTH Frontman Pays Tribute To SLAYER's JEFF HANNEMAN””Slayer, Hatebreed Doing Double Duty On This Year's Ozzfest””System of a Down””Lacuna Coil’s Andrea Ferro Talks Influences, Skateboarding, Band Origins + More””Slayer - Reign in Blood””Into The Lungs of Hell””Slayer rules - en utställning om fans””Slayer and Their Fans Slashed Through a No-Holds-Barred Night at Gas Monkey””Home””Slayer””Gold & Platinum - The Big 4 Live from Sofia, Bulgaria””Exclusive! Interview With Slayer Guitarist Kerry King””2008-02-23: Wiltern, Los Angeles, CA, USA””Slayer's Kerry King To Perform With Megadeth Tonight! - Oct. 21, 2010”originalet”Dave Lombardo - Biography”Slayer Case DismissedArkiveradUltimate Classic Rock: Slayer guitarist Jeff Hanneman dead at 49.”Slayer: "We could never do any thing like Some Kind Of Monster..."””Cannibal Corpse'S Pat O'Brien Will Step In As Slayer'S Guest Guitarist | The Official Slayer Site”originalet”Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Kerrang! Awards 2006 Blog: Kerrang! Hall Of Fame””Kerrang! Awards 2013: Kerrang! Legend”originalet”Metallica, Slayer, Iron Maien Among Winners At Metal Hammer Awards””Metal Hammer Golden Gods Awards””Bullet For My Valentine Booed At Metal Hammer Golden Gods Awards””Metal Storm Awards 2006””Metal Storm Awards 2015””Slayer's Concert History””Slayer - Relationships””Slayer - Releases”Slayers officiella webbplatsSlayer på MusicBrainzOfficiell webbplatsSlayerSlayerr1373445760000 0001 1540 47353068615-5086262726cb13906545x(data)6033143kn20030215029