Error exception ioexception is never thrown in body of corresponding try statement

I receive an error each time. What am I doing wrong? My Code: public static void hashMap(String crnString) { try { if (mMap.containsKey(crnString)) { int cou...

I receive an error each time. What am I doing wrong?

My Code:

 public static void hashMap(String crnString)
{
    try
    {
        if (mMap.containsKey(crnString))
        {
            int count = mMap.get(crnString);
            count++;
            mMap.put(crnString, count);
        }
        else
        {
            mMap.put(crnString, 1);
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
    }
}

user207421's user avatar

asked Oct 11, 2013 at 2:05

GirlWhoCodes's user avatar

4

Assuming mMap is a HashMap, the code inside the try block never throws an IOException. Remove the try-catch block wrapping your code.

public static void hashMap(String crnString){
    if (mMap.containsKey(crnString)) {
        int count = mMap.get(crnString);
        count++;
        mMap.put(crnString, count);
    } else {
        mMap.put(crnString, 1);
    }
}

answered Oct 11, 2013 at 2:07

Sotirios Delimanolis's user avatar

3

IOException is checked exception. So code in try block is not potential code that can raise IOExcption that’s why the compiler shows error. Use specific exception type catch block that can be raised or use unchecked exception catch block. In you try block code, only NPE can be raised.

  try
{
    if (mMap.containsKey(crnString))
    {
        int count = mMap.get(crnString);
        count++;
        mMap.put(crnString, count);
    }
    else
    {
        mMap.put(crnString, 1);
    }
} catch (NullPointerException e)
{
    e.printStackTrace();
} catch(Exception e) {
   System.out.println("Unexcepted Exception");
    e.printStackTrace();
}
finally
{
}

answered Oct 11, 2013 at 2:36

Vallabh Patade's user avatar

Vallabh PatadeVallabh Patade

4,8806 gold badges31 silver badges40 bronze badges

2

I am not too stupid to realize that the code in the ‘try catch’ cannot throw an exception. But I am stuck here because I have copied the code exactly from the book so it must have been correct when published. It’s left me wondering if the code can’t compile anymore because it’s out of date? I realize the nature of this question may offend some people here. If so please just don’t be TOO harsh in your stern reprimands.

I am getting the error :

./StreamCopier.java:13: error: exception IOException is never thrown in body of corresponding try statement
} catch (IOException e) {System.err.println(e);}

//FileTyper.java
//Reads filenames from the command line and copies named files onto System.out.

import java.io.*;

public class FileTyper  {

  public static void main (String[] args)  {

    if (args.length == 0)  {
      System.err.print("usage: java FileTyper file1, file2");
      return;
    }

    for (int i = 0 ; i < args.length ; i++)  {
      try  {
        typeFile(args[i]);
        if (i+1 < args.length)  {    //more files waiting to be processed
          System.out.println();
          System.out.println("********************************************");
        }
      } catch (IOException e) {System.err.println(e);}
    } //end for

  } //end main()

  public static void typeFile (String filename) throws IOException  {

    FileInputStream fin = new FileInputStream(filename);
    StreamCopier.copy(fin, System.out);
    fin.close();
  }
}


//StreamCopier.java
//hard to know what this program does exactly

import java.io.*;

public class StreamCopier  {

  public static void main (String[] args)  {

    try  {

    } catch (IOException e) {System.err.println(e);}

  }

  public static void copy (InputStream in, OutputStream out) throws IOException  {

    //do not allow other threads to read from the  input or
    //write to the output while copying is taking place.
    synchronized (in)  {
      synchronized (out)  {
        byte [] buffer = new byte [256];
        while (true) {
          int bytesRead = in.read(buffer);
          if (bytesRead == -1) break;
          out.write(buffer, 0, bytesRead);
        }
      }
    }

  }  //end copy()

} 

VMai's user avatar

VMai

10.1k9 gold badges24 silver badges34 bronze badges

asked Aug 24, 2014 at 9:25

user3814983's user avatar

6

The error is because of the empty try {} catch {} block in the main method of StreamCopier.java. Remove the empty try{} catch{} block and then try. It should work.

public static void main (String[] args)  {
            try  {


            } catch (IOException e) {System.err.println(e);} // here is the problem
}

answered Aug 24, 2014 at 9:44

Loganathan Mohanraj's user avatar

The try block is empty, apparently because you haven’t written the code that goes in it yet. The Java compiler stupidly complains if there is a catch block and [it thinks] the exception cannot be thrown. This is one of the annoying qualities of Java’s checked exceptions.

Simply continue to fill in the try block, and the error will go away. You can insert a dummy copy(null, null); inside it to make the compiler shut up.

answered Aug 24, 2014 at 9:45

Boann's user avatar

BoannBoann

48.3k15 gold badges117 silver badges146 bronze badges

3

Содержание

  1. «Exception is never thrown in body of corresponding try statement.» When does this error occur?
  2. exception java.lang.InterruptedException is never thrown in body of corresponding try statement
  3. компилятор java говорит, что это исключение никогда не выбрасывается в теле соответствующего оператора try-но оно выбрасывается
  4. 5 ответов

«Exception is never thrown in body of corresponding try statement.» When does this error occur?

  • I got the Compiler error «IOException is never thrown in body of corresponding try statement» for the below code. But I have got no error when I caught «NumberFormatException» instead of «IOException». When does this error occur? And when does it not??

    public class abc
    <

    public static void main(String args[]) throws Exception
    <
    try
    <
    System.out.println(«Try «);
    >
    catch (IOException e) <>
    finally
    <
    System.out.println(«Finally «);
    >
    >
    >

    Thank you,
    Bindu.

  • IOException can never occur from System.out.println(). But NUmberFormatException can occur in the following case :

    I hope this clears your doubt.

  • If the underlying stream is a socket stream and the network dies while you’re reading, if you’re attempting to read from a stream that’s been closed, etc.There are many instances where the IOException will be raised. If you want to raise the IOException you can do it explicitly by using keyword throw.Look at the following code which will throw the IOException explicitly.

  • Thank you Koushik and James.

    What I understood is that, Compiler does not generate an Error if we try to catch an Exception that might possibly be thrown in the try block. But if there is absolutely no possibility of that Exception occurring in the try block, then the Compiler would complain.

    I guess an empty try block guarantees no exceptions, whatsoever. In this case, compiler should complain if we try to catch any kind of Exception. But, I still see no error in case of NumberFormatException and error in case of IOException. Why is this discrepancy?

    >
    catch (NumberFormatException e) <>

    Thank you,
    Bindu.

  • Bindu Tadivaka wrote: Thank you Koushik and James.

    What I understood is that, Compiler does not generate an Error if we try to catch an Exception that might possibly be thrown in the try block. But if there is absolutely no possibility of that Exception occurring in the try block, then the Compiler would complain.

    I guess an empty try block guarantees no exceptions, whatsoever. In this case, compiler should complain if we try to catch any kind of Exception. But, I still see no error in case of NumberFormatException and error in case of IOException. Why is this discrepancy?

    The compiler only error checks checked exceptions — hence, the name. IOException is a checked exception. NumberFormatException is an unchecked exception.

    Источник

    exception java.lang.InterruptedException is never thrown in body of corresponding try statement

  • Any idea why I am getting a compilation error, and, how I could go about it?

    Source Core Java Vol.2 (7th Ed.) written for JDK 1.5.

    Error java:52: exception java.lang.InterruptedException is never thrown in body of corresponding try statement catch (InterruptedException e)

  • Read the error message from the compiler carefully.

    What do you think it is trying to tell you?

  • John Jai wrote: Were you able to figure out the source of error in the below code?

    Well is it safe to remove the catch? In any case the ‘ball’ does not seem to move anywhere with this code, when I remove the catch clause.

  • Jon Camilleri wrote: Well is it safe to remove the catch? In any case the ‘ball’ does not seem to move anywhere with this code, when I remove the catch clause.

    So, let’s look at the error message from the compiler:

    exception java.lang.InterruptedException is never thrown in body of corresponding try statement catch (InterruptedException e)

    Read it carefully and try to understand it. What does it say? It says that in the try-block there isn’t any code that can ever throw InterruptedException. In other words, catching InterruptedException is unnecessary here, because it will never be thrown from the try-block.

    So, what do you think, is it safe to remove the catch?

  • Jon Camilleri wrote: Well is it safe to remove the catch? In any case the ‘ball’ does not seem to move anywhere with this code, when I remove the catch clause.

    So, let’s look at the error message from the compiler:

    exception java.lang.InterruptedException is never thrown in body of corresponding try statement catch (InterruptedException e)

    Read it carefully and try to understand it. What does it say? It says that in the try-block there isn’t any code that can ever throw InterruptedException. In other words, catching InterruptedException is unnecessary here, because it will never be thrown from the try-block.

    So, what do you think, is it safe to remove the catch?

    Horstmann reads that the catch is recommended to be there, whilst the compiler thinks that it is not.

    Источник

    компилятор java говорит, что это исключение никогда не выбрасывается в теле соответствующего оператора try-но оно выбрасывается

    у меня есть следующий код:

    когда выше запускается с неправильным именем хоста, я получаю:

    это правильно и ожидается. Я переписал код, чтобы специально поймать UnknownHostException, следующим образом:

    однако, когда я пытаюсь скомпилировать это, я получаю:

    это явно ложно, так как исключение брошено, как я поймал его раньше. Я что-то упускаю?

    5 ответов

    это не бросать UnknownHostException . Он просто появляется в исключения, вы на самом деле поймали. Вероятно, это основная причина исключения, которое вы поймали.

    определить фактический исключение, вы должны напечатать немного больше деталей. Е. Г.

    или просто с помощью Throwable#toString() , которая уже включает в себя как тип исключения и сообщение:

    или просто передать исключение в качестве 2-й аргумент logger, если хорошо настроен, его stacktrace будет напечатан:

    обновление в соответствии с вашими комментариями: лучше всего обновить улов следующим образом:

    вы абсолютно не должны различать на основе сообщения. Это проблема переносимости. Сообщение является чувствительной темой для изменений, которые могут даже зависеть от локали!

    существуют различные тонкие (или в некоторых случаях неубедительные) способы создания проверенных исключений в ситуациях, когда они явно не объявлены. Некоторые перечислены на этой странице.

    просто мысль, может быть, это UnknownHostException в другой упаковке?

    e.getMessage () дает вам вывод, указывающий, что UnknownHostException происходит где-то, но, возможно, код за портом.login () somewhere ловит UnknownHostException ,бросая другое исключение и указывая в сообщении этого исключения, что UnknownHostException было исходным исключением (или, возможно, его цепочкой). Трудно сказать, не зная, какой точный тип исключения пойман в вашем оригинальном блоке catch. Узнайте это сначала (возможно, просто сделав е.печатные() ) и это должно сказать вам, что вы должны ловить.

    на android я видел это, но на самом деле это проходило как UndeclaredThrowableException . Так что вместо того, чтобы ловить UnknownHostException , Я только что поймал UndeclaredThrowableException .

    Источник


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Hi,

    I’m currently in the Exceptions section (of my java course) and my program below relates to the same.

    About the program:

    To take input from the user a number (integer), check whether its prime number or not and display the appropriate message to standard output.

    Issue faced:

    The exception thrown is IOException and the catch block should handle the same. However, the IDE (netbeans 6.0) does not allow this

    and highlights with the message exception java.io.IOException is never thrown in body of corresponding try statement. When i modified the catch statement by passing Exception class, IDE allows this. At run-time, when i input a string (say java) instead of a number, the error shown is Exception in thread «main» java.util.InputMismatchException (if the catch handler is modified to Exception).

    My questions:

    1. Why does the IDE not allow IOException to be caught where its thrown and

    2. once modified to Exception, the exception raised is java.util.InputMismatchException and not java.io.IOException. Why?

    I also modified the below program wherein the PrimeNum class with the method getPrimeNum throws the IOException and this is caught by the TestPrimeNum class. The exception raised (on input of string) again is Exception in thread «main» java.util.InputMismatchException instead of java.io.IOException.

    Could any of the expert(s) please explain this.

    thanks,

    Sudhir

    Original code:

    —————-

    Modified code:

    ——————


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    From the javadocs

    IOException signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations

    This exception is thrown only when the code fails to read/write data. A string instead of an int (like in your code) would throw InputMismatchException because there is an obvious mismatch — it expects an int but the input was a String.

    Ranch Hand

    Posts: 1376

    Eclipse IDE
    Java


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    1. Mentioning throws IOException in method signature does not bind us to catch that same exception within method.

    2. IOException is never thrown in body of corresponding try statement error is coming because there is no code within try block which throw IOException.

    IDE gives error because when we save (Ctrl+S) any java file in IDE(Eclipse,Netbeans etc), IDE complies that java file for us (means ruuning javac command for us).

    I hope you have covered Checked and Unchecked Exceptions topic in your course/training.

    IOException is an checked exception which means code is checked during compile time for any piece of code which throws IOException and whether it is properly handled or not. We can either catch a checked exception using catch block OR add a throws clause in method signature.

    Now coming to your code, you have added a catch clause for IOException but code within try block do not throw IOException.

    To remove this exception, i am just adding a throw clause deliberately in your code. When this is added(as shown in code below) , IDE will not give error.

    Reason — we have now deliberately thrown IOException in try block which has been properly handled in catch(IOException) block.

    So bottom line is — we are not required to catch IOException until unless it is thrown from code present within try block.

    3. Reason we are getting InputMismatchException — nextInt() method of Scanner class throws InputMismatchException if input mismatch happens. So if String is passed instead of int, this method throw this exception.

    ~ abhay


    posted 11 years ago


    • Likes 1
    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:1. Why does the IDE not allow IOException to be caught where its thrown

    When any method / constructor inside the try block can throw an IOException, you’ll be able to catch it. But nothing in your try block will ever throw an IOException, therefore you cannot catch it.

    2. once modified to Exception, the exception raised is java.util.InputMismatchException and not java.io.IOException. Why?

    Because that’s the exception that’s actually being thrown. InputMismatchException is an indirect sub class of RuntimeException. That means that methods / constructors do not need to explicitly include it in a throws clause. And because it’s a RuntimeException, it’s also an Exception. That’s why you’ll always be able to catch Exception.

    Marshal

    Posts: 77296


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Sridhar Santhanakrishnan wrote:. . . A string instead of an int (like in your code) would throw InputMismatchException because there is an obvious mismatch — it expects an int but the input was a String.

    Not quite. It receives a String but the String must match an

    int

    . You cannot pass 123 to a Scanner. But you can pass

    «123»

    which is a String-OK for nextInt(). If, however, you pass

    «Campbell»

    or

    «123.45»

    or

    «9999999999999999999999999999»

    which are all invalid for conversion to an

    int

    , you will suffer an InputMismatchException.

    Sudhir Srinivasan

    Ranch Hand

    Posts: 93


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Thank you Abhay, Rob and Campbell……certainly have more clarity now on the InputMismatchException Vs IOException tangle.

    From Rob’s and Campbell’s responses — Irrespective of the IOException being thrown from within the present code of the try block and handled by the following catch OR thrown and caught elsewhere, the exception raised would always be InputMismatchException when user inputs «java» or «sudhir» etc. [as they are not string representation of int]

    Abhay, your detailed explanation of IDE error

    IOException is never thrown in body of corresponding try statement error is coming because there is no code within try block which throw IOException.

    IDE gives error because when we save (Ctrl+S) any java file in IDE(Eclipse,Netbeans etc), IDE complies that java file for us (means ruuning javac command for us).

    I hope you have covered Checked and Unchecked Exceptions topic in your course/training.

    IOException is an checked exception which means code is checked during compile time for any piece of code which throws IOException and whether it is properly handled or not. We can either catch a checked exception using catch block OR add a throws clause in method signature.

    Now coming to your code, you have added a catch clause for IOException but code within try block do not throw IOException.

    To remove this exception, i am just adding a throw clause deliberately in your code. When this is added(as shown in code below) , IDE will not give error.

    Reason — we have now deliberately thrown IOException in try block which has been properly handled in catch(IOException) block.

    So bottom line is — we are not required to catch IOException until unless it is thrown from code present within try block.

    has helped in resolving the same. However, the exception raised would still conform to the other responders explanations.

    many thanks,

    Sudhir

    Campbell Ritchie

    Marshal

    Posts: 77296


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    If you use a Scanner, it consumes any IOExceptions, but there is a method in Scanner which allows you to retrieve its most recent IOException; I think it is called ioException. You can call that method on a Scanner and thorw that Exception (but make sure to use a

    null

    test because the

    throw

    keyword doesn’t react well to

    null

    s ).

    You can also find that the nextXXX methods of Scanner throw the InputMismatchException, if you go through the API (scroll up and down from the earlier link). If you look up InputMismatchException, you find it is because the input was not in the correct format.

    Also (Rob told me how to do this), if you go into the InputMismatchException API page and click on Use at the top, it tells you that thsi Exception is only thrown by Scanner.

    At least it used to the page isn’t working any more. But the API does say «thrown by a Scanner».

    You do realise that an IOException is completely different? It might be caused by trying to write to a read-only File, or a loose wire, or some network problem, so you are not getting input or output. You might suffer one of its subclasses instead. If you get an InputMismatchException, you have got some input, but the wrong format.

    Campbell Ritchie

    Marshal

    Posts: 77296


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:

    Thank you Abhay, Rob and Campbell…..

    You’re welcome

    Sudhir Srinivasan

    Ranch Hand

    Posts: 93


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:

    You do realise that an IOException is completely different? It might be caused by trying to write to a read-only File, or a loose wire, or some network problem, so you are not getting input or output. You might suffer one of its subclasses instead. If you get an InputMismatchException, you have got some input, but the wrong format.

    I’ve now completely understood that IOException occurs when the code is unable to perform the read/write operations at runtime whereas an InputMismatchException is thrown up when the data input is read but is not the type what the Scanner class expects (in my case, string instead of int).

    As per your suggestion


    If you use a Scanner, it consumes any IOExceptions, but there is a method in Scanner which allows you to retrieve its most recent IOException; I think it is called ioException. You can call that method on a Scanner and thorw that Exception (but make sure to use a null test because the throw keyword doesn’t react well to nulls ).

    i modified my code further as

    On line 10 i’ve written the InputStreamReader class with the scan object reference providing the wrap-around for the same in the next line. Lines 29 and 30 invoke the ioException() of the Scanner and throws the IOException. On program execution:

    [output]

    init:

    deps-jar:

    compile-single:

    run-single:

    Enter a number(0 to exit):

    12

    You have input: 12

    Number input 12 is not a prime

    Enter a number(0 to exit):

    3

    You have input: 3

    Number input 3 is a prime

    Enter a number(0 to exit):

    8

    You have input: 8

    Number input 8 is not a prime

    Enter a number(0 to exit):

    0

    java.io.IOException

    null

    at PrimeNum.getPrimeNum(PrimeNum.java:37)

    at TestPrimeNum.main(TestPrimeNum.java:8)

    BUILD SUCCESSFUL (total time: 15 seconds)

    [/output]

    returns the IOException thrown for the last input(zero) by the Scanner’s underlying readable, InputStreamReader. null indicates no such exception exists in this case.

    once again, thanks for the inputs and javadocs reference(s).

    Sudhir

    Campbell Ritchie

    Marshal

    Posts: 77296


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Why on earth are you throwing a new IOException? That is not what the ioException method is for. You check whether it is

    null

    , and if it isn’t, you can throw it. You don’t want a diffrent Exception.

    And never say

    == true

    or

    == false

    . Write

    if (flag) …

    or

    if (!flag) …

    Not only is that poor style, but also error-prone because you might write = by mistake.

    Sudhir Srinivasan

    Ranch Hand

    Posts: 93


    posted 11 years ago

    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:Why on earth are you throwing a new IOException? That is not what the ioException method is for. You check whether it is null, and if it isn’t, you can throw it. You don’t want a diffrent Exception.

    Oops…..sorry about that! Yes, the «throw new IOException» statement is not required when the ioException method of IOException is invoked.

    Campbell Ritchie wrote:And never say == true or == false. Write if (flag) … or if (!flag) … Not only is that poor style, but also error-prone because you might write = by mistake.

    As suggested, i’ll certainly conform to the if(flag) boolean expression within the if statement rather than if(flag == true) though i’m clear in the distinction between = (assignment operator) and == (equals operator).

    Continuing on the subject of IOException:

    java.lang.Object

    extended byjava.lang.Throwable

    extended byjava.lang.Exception

    extended byjava.io.IOException

    a) Why does IOException [subclass of Exception class] form part of the java.io package and not of the language package to which the Exception class belongs to?

    b) are there any other IOExceptions besides EOFException, FileNotFoundException?

    thanks and regards,

    Sudhir


    posted 11 years ago


    • Likes 2
    • Mark post as helpful


    • send pies

      Number of slices to send:

      Optional ‘thank-you’ note:



    • Quote
    • Report post to moderator

    Sudhir Srinivasan wrote:i’m clear in the distinction between = (assignment operator) and == (equals operator).

    You may be but are your fingers ? It’s very easy to accidentally type = instead of ==. Doing it how Campbell suggest removes this possibility.

    Sudhir Srinivasan wrote:are there any other IOExceptions besides EOFException, FileNotFoundException?

    Notice in your post (and this one) that the word IOException has been turned into a link. Click on the link and you will get the answer to your question.

    Joanne

    jQuery in Action, 3rd edition

    1. Overview

    In this tutorial, we’ll look at the Lombok @SneakyThrows annotation.

    2. Maven Dependency

    We’ll first add the Lombok maven dependency:

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.8</version>
    </dependency>

    3. Use @SneakyThrows

    Java requires that we must either declare or handle a checked exception. Otherwise, the code won’t compile. But @SneakyThrows lets us bypass this rule.

    For instance, when we call a method that throws an IOException, we must either declare the IOException in our own method:

    public void throwsCheckedAndDeclares() throws IOException {
        throw new IOException("Checked exception");
    }

    Or we must handle it with a try-catch block:

    public void throwsCheckedAndHandles() {
        try {
            throw new IOException("Checked exception");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    Note that this rule is only valid for checked exceptions. We don’t need to handle or declare unchecked exceptions:

    public void throwsUncheckedAndSkips() {
        throw new RuntimeException("Unchecked exception");
    }

    Here, we’re throwing RuntimeException which is an unchecked exception.

    Now that we’ve seen the regular usage, let’s look at the usage of @SneakyThrows:

    @SneakyThrows
    public void sneakyThrowsCheckedAndSkips() {
        throw new IOException("Checked exception");
    }

    Although we throw an IOException here, we aren’t declaring or handling. @SneakyThrows fakes out the compiler. In other words, Lombok doesn’t wrap or replace the thrown checked exception but makes the compiler think that it is an unchecked exception.

    Let’s see another way to achieve the same result:

    public void sneakyThrowsCheckedAndSkipsWithLombok() {
        try {
            throw new IOException("Checked exception");
        } catch (IOException e) {
            Lombok.sneakyThrow(e);
        }
    }

    In this code, we’re catching the IOException and calling Lombok.sneakyThrow. In return, it just throws the same exception without any modification.

    This is possible because JVM isn’t aware of the distinction between checked and unchecked exceptions. Moreover, it doesn’t enforce the handle-or-declare rule. This rule is enforced by the Java compiler. Consequently, when we deceive the Java compiler, our code just runs fine.

    We generally catch a checked exception and wrap it inside a RuntimeException, and then throw it. @SneakyThrows reduces the number of this pattern, as a result, making the code more readable.

    3.1. Configure Exception Types

    We can also configure the exception types that we want to sneakily throw, in the value attribute of @SneakyThrows.

    @SneakyThrows({IOException.class, ParseException.class})
    public void filtersExceptions(String fileName) {
        if (fileName.startsWith("0")) {
            throw new ParseException("test", 1);
        } else {
            throw new IOException();
        }
    }

    The important point here is that if we list an exception that can’t be thrown from the method body, the code won’t compile.

    3.2 Implications of Using @SneakyThrows

    We can’t catch sneakily thrown checked exceptions directly. This is because the Java compiler expects the exception type declared as thrown in one of the invoked methods.

    Let’s see with an example.

    Previously, we defined the sneakyThrowsCheckedAndSkips method. When we call it from another method and try to catch IOException:

    public void callSneakingThrowingChecked() {
        try {
            sampleService.sneakyThrowsCheckedAndSkips();
        } catch (IOException e) { // java: exception java.io.IOException is never thrown in body of corresponding try statement
            System.out.println(e);
        }
    }

    The compiler says that «java.io.IOException is never thrown in body of corresponding try statement«. Although sneakyThrowsCheckedAndSkips throws IOException, the compiler isn’t aware of it. Hence the compilation fails.

    As a workaround, we can use a parent type — like Exception — in the catch block:

    public void callSneakingThrowingChecked() {
        try {
            sampleService.sneakyThrowsCheckedAndSkips();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    After this change, the code compiles and the calling code can catch the sneakily thrown IOException.

    4. Global Configuration

    Lombok provides some configuration keys for the annotations to globally configure them.

    4.1. lombok.sneakyThrows.flagUsage

    We can set the lombok.sneakyThrows.flagUsage property to forbid the use of @SneakyThrows:

    # [warning | error] (default: not set)
    lombok.sneakyThrows.flagUsage = error

    There is no default value for this property, and we’re setting it as error. As a result, when Lombok detects usage of @SneakyThrows, it prints an error message like «Use of @SneakyThrows is flagged according to lombok configuration.«

    5. Summary

    In this tutorial, we’ve investigated the usage of Lombok @SneakyThrows.

    As always, the source code for all examples is available on Github.

    Не пропускает, помогите, плиз

    Solution 24 строка. Подскажите, плиз, что не так )
    Если быть точнее, то
    неизвестная ошибка компиляции
    ioexception is never thrown in body of corresponding try statement

    package com.javarush.task.task15.task1522;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;

    /*
    Закрепляем паттерн Singleton
    */

    public class Solution {
    public static void main(String[] args) {

    }

    public static Planet thePlanet;

    //add static block here — добавьте статический блок тут
    static {
    try {
    readKeyFromConsoleAndInitPlanet();
    }

    catch (IOException e) {
    e.printStackTrace();
    }
    }

    public static void readKeyFromConsoleAndInitPlanet() {
    // implement step #5 here — реализуйте задание №5 тут
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
    String s;
    if ((s = br.readLine()).equals(Planet.EARTH)) {
    thePlanet = (Planet) Earth.getInstance();
    }
    if (s.equals(Planet.MOON)) {
    thePlanet = (Planet) Moon.getInstance();
    }

    if (s.equals(Planet.SUN)) {
    thePlanet = (Planet) Sun.getInstance();
    }
    } catch (Exception e) {
    thePlanet = null;
    }
    br.close();
    }
    }

    Этот веб-сайт использует данные cookie, чтобы настроить персонально под вас работу сервиса. Используя веб-сайт, вы даете согласие на применение данных cookie. Больше подробностей — в нашем Пользовательском соглашении.

    Welcome to the Treehouse Community

    The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

    Looking to learn something new?

    Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

    i followed along with the video, making a weather app. but on the onResponse method of a CallBack i get the above error.

    Code:

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
    
            }
    
            @Override
            public void onResponse(Call call, Response response) throws IOException  {
                Log.v(TAG, response.body().string());
                try {
                    if (response.isSuccessful()) {
    
                    }
                    else {
                        alertUserAboutError();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "IO Exception caught", e);
                }
            }
        });
    

    1 Answer

    Martin Klestil

    It’s a small bug, he can not write a log because the tag only exists locally in the if block. Copy Log.v (TAG, response.body (). String ()); in front of the if block.

    I hope this helps you.

    @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        Log.v(TAG, response.body().string());
                        if (response.isSuccessful()) {
    
                        }
                        else{
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "IO Exception caught: ", e);
                    }
                }
    

    у меня есть следующий код:

    try {
        //jaw-ws service port operation
        port.login();
    } catch (Exception e) {
        logger.error("Caught Exception in login(): " + e.getMessage());
    }
    

    когда выше запускается с неправильным именем хоста, я получаю:

    Caught Exception in login(): HTTP transport error: java.net.UnknownHostException: abc
    

    это правильно и ожидается. Я переписал код, чтобы специально поймать UnknownHostException, следующим образом:

    import java.net.UnknownHostException;
    try {
        //jaw-ws service port operation
        port.login();
    } catch (UnknownHostException uhe) {
        //do something specific to unknown host exception
    } catch (Exception e) {
        logger.error(Caught Exception in login(): " + e.getMessage());
    }
    

    однако, когда я пытаюсь скомпилировать это, я получаю:

    [javac] foo.java: exception java.net.UnknownHostException is never thrown in body of corresponding try statement
    [javac]         } catch (UnknownHostException uhe) {
    [javac]                  ^
    

    это явно ложно, так как исключение брошено, как я поймал его раньше. Я что-то упускаю?

    tia,
    рубль

    5 ответов


    это не бросать UnknownHostException. Он просто появляется в исключения, вы на самом деле поймали. Вероятно, это основная причина исключения, которое вы поймали.

    определить фактический исключение, вы должны напечатать немного больше деталей. Е. Г.

    } catch (Exception e) {
        logger.error("Caught Exception in login(): " + e.getClass().getName() + ": " + e.getMessage());
    }
    

    или просто с помощью Throwable#toString(), которая уже включает в себя как тип исключения и сообщение:

    } catch (Exception e) {
        logger.error("Caught Exception in login(): " + e);
    }
    

    или просто передать исключение в качестве 2-й аргумент logger, если хорошо настроен, его stacktrace будет напечатан:

    } catch (Exception e) {
        logger.error("Caught Exception in login(): " + e.getMessage(), e);
    }
    

    обновление в соответствии с вашими комментариями: лучше всего обновить улов следующим образом:

    } catch (ClientTransportException e) {
        if (e.getCause() instanceof UnknownHostException) {
            // UHE.
        } else {
            // Other.
        }
    }
    

    вы абсолютно не должны различать на основе сообщения. Это проблема переносимости. Сообщение является чувствительной темой для изменений, которые могут даже зависеть от локали!


    существуют различные тонкие (или в некоторых случаях неубедительные) способы создания проверенных исключений в ситуациях, когда они явно не объявлены. Некоторые перечислены на этой странице.


    просто мысль, может быть, это UnknownHostException в другой упаковке?


    e.getMessage () дает вам вывод, указывающий, что UnknownHostException происходит где-то, но, возможно, код за портом.login () somewhere ловит UnknownHostException ,бросая другое исключение и указывая в сообщении этого исключения, что UnknownHostException было исходным исключением (или, возможно, его цепочкой). Трудно сказать, не зная, какой точный тип исключения пойман в вашем оригинальном блоке catch. Узнайте это сначала (возможно, просто сделав е.печатные() ) и это должно сказать вам, что вы должны ловить.


    на android я видел это, но на самом деле это проходило как UndeclaredThrowableException. Так что вместо того, чтобы ловить UnknownHostException, Я только что поймал UndeclaredThrowableException.


    Понравилась статья? Поделить с друзьями:
  • Error exception in steamclient dll at offset 0x01d00000
  • Error eperm operation not permitted open discord
  • Error exception in asgi application fastapi
  • Error exception handling disabled use fexceptions to enable
  • Error exception handling console input java io ioexception неверный дескриптор