Why does the compiler allow throws when the method will never throw the Exception The Next CEO of Stack OverflowHow 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?

How exploitable/balanced is this homebrew spell: Spell Permanency?

Why did early computer designers eschew integers?

Could a dragon use its wings to swim?

Is it possible to create a QR code using text?

Why was Sir Cadogan fired?

Incomplete cube

Prodigo = pro + ago?

Does the Idaho Potato Commission associate potato skins with healthy eating?

Is it possible to make a 9x9 table fit within the default margins?

How to coordinate airplane tickets?

How to find if SQL server backup is encrypted with TDE without restoring the backup

Which acid/base does a strong base/acid react when added to a buffer solution?

Is it "common practice in Fourier transform spectroscopy to multiply the measured interferogram by an apodizing function"? If so, why?

Why does the freezing point matter when picking cooler ice packs?

Why did the Drakh emissary look so blurred in S04:E11 "Lines of Communication"?

How to compactly explain secondary and tertiary characters without resorting to stereotypes?

How can I separate the number from the unit in argument?

Is it a bad idea to plug the other end of ESD strap to wall ground?

Car headlights in a world without electricity

Why can't we say "I have been having a dog"?

Find a path from s to t using as few red nodes as possible

Are British MPs missing the point, with these 'Indicative Votes'?

How seriously should I take size and weight limits of hand luggage?

Gauss' Posthumous Publications?



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



The Next CEO of Stack OverflowHow 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?










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

















  • 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
















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

















  • 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














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














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

785




785







  • 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


















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









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















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













      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 Mar 25 at 9:53

























      answered Mar 25 at 9:43









      EranEran

      291k37479563




      291k37479563







      • 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

      547k588941021




      547k588941021







      • 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

          423




          423





















              -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

                      Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

                      Tähtien Talli Jäsenet | Lähteet | NavigointivalikkoSuomen Hippos – Tähtien Talli

                      Do these cracks on my tires look bad? The Next CEO of Stack OverflowDry rot tire should I replace?Having to replace tiresFishtailed so easily? Bad tires? ABS?Filling the tires with something other than air, to avoid puncture hassles?Used Michelin tires safe to install?Do these tyre cracks necessitate replacement?Rumbling noise: tires or mechanicalIs it possible to fix noisy feathered tires?Are bad winter tires still better than summer tires in winter?Torque converter failure - Related to replacing only 2 tires?Why use snow tires on all 4 wheels on 2-wheel-drive cars?