try-catch & throw Exception Question

M

Matt

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

}
 
M

Michael Rauscher

Matt said:
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.

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top