try-catch & throw Exception Question

Discussion in 'Java' started by Matt, Jun 12, 2004.

  1. Matt

    Matt Guest

    Method evenNumber can throw IOException, and the caller of method
    evenNumber (in this case, method evenNumberTest and method evenNumberTest2)
    should catch the IOException. Otherwise, it will have compile
    error as the one in method evenNumberTest2.

    My question is when I run the program, it will have output "catch evenNumberTest",
    but it doesn't output "throw testNumber" Why is that?

    I thought ""throw new IOException("throw testNumber");"" will print
    "throw testNumber" when it throws the IOException.

    So in what situation "throw testNumber" will print it out??

    Please advise. Thanks!!

    ==========================================================
    import java.io.*;
    public class ExceptionTest
    {
    private void evenNumberTest()
    { try
    { evenNumber(2);
    }
    catch(IOException e)
    { System.out.println("catch evenNumberTest");
    }
    }

    /**
    ExceptionTest.java:14: unreported exception java.io.IOException; must be caught
    or declared to be thrown
    { evenNumber(2);
    ^
    private void evenNumberTest2()
    { evenNumber(2);
    }

    */
    private void evenNumber(int x) throws IOException {
    if (x % 2 == 0)
    throw new IOException("throw testNumber");
    }

    public static void main(String[] args)
    { ExceptionTest e = new ExceptionTest();
    e.evenNumberTest();
    }

    }
     
    Matt, Jun 12, 2004
    #1
    1. Advertisements

  2. No. throw prints nothing. To print the message of a given exception "e",
    you could request it via e.getMessage(), e.g.

    catch ( IOException e ) {
    System.err.println("catched evenNumberTest: " + e.getMessage() );
    }

    Bye
    Michael
     
    Michael Rauscher, Jun 12, 2004
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.