File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can constructors throw exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "can constructors throw exceptions" Watch "can constructors throw exceptions" New topic
Author

can constructors throw exceptions

prasanthi kothapa
Ranch Hand

Joined: Oct 19, 2000
Posts: 30
can any one explain this piece of code:
what is wrong with it??
the compiler says the exception must be caught,
but it's handled by the throws isn't it ??

public class Test {
int x = 0;

public Test(int inVal) throws Exception{
if (inVal != this.x){
throw new Exception("Invalid input");
}
}
public static void main(String args[]){
Test t = new Test(4);
}
}

thanx,
prasanthi
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 2547
>the compiler says the exception must be caught,
>but it's handled by the throws isn't it ??
'throws' does not handle an exception, in fact, it makes the caller handle the exception!
>public Test(int inVal) throws Exception
This means: I'm going to throw an exception, you better handle it.

>Test t = new Test(4);
Now, here you should either catch the exception thrown by Test(4) or pass it on by declaring it in the throws clause of the main method.
Handling a Constructor that throws an exception is same as handling a method that throws an exception.
HTH,
Paul.

------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern)
www.enthuware.com/jqplus


Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
prasanthi kothapa
Ranch Hand

Joined: Oct 19, 2000
Posts: 30
I got your point.i didn't realize it.thanks
a lot paul.

thanks again.
prasanthi
 
 
subject: can constructors throw exceptions
 
Threads others viewed
clone method
Another question for NPE.........
finalize() method invoked by the garbage collector
another question regarding garbage collection
How to test a method, which throws Exception in Junit?
MyEclipse, The Clear Choice