Java Reference
In-Depth Information
public Test(int x) throws CException {
// Code goes here
}
// Rest of the code goes here
}
You must handle the CException when you create an object of the Test class using any of its constructors as
Test t = null;
try {
t = new Test();
}
catch (CException e) {
// Handle exception here
}
If you do not handle the CException using a try-catch block, you must use a throws clause to specify that the
method or constructor that uses the constructor of the Test class may throw CException .
If an instance initializer throws a checked exception, you must declare a constructor for your class. The compiler
will add a default constructor to your class if you do not add one. However, the compiler will not add a throws clause
to the default constructor, which will break the above rule. The following code will not compile:
public class Test123 {
{
// May throw CException, which is a checked exception.
}
}
When the Test123 class is compiled, the compiler adds a default constructor, and the class Test123 will look
as follows:
public class Test123 {
{
// May throw CException, which is a checked exception.
}
public Test123() {
// An empty body. The compiler did not add a throws clause.
}
}
Note that the default constructor, which was added by the compiler, does not contain a throws clause to include
CException , which is thrown by the instance initializer. This is the reason that the Test123 class will not compile. To
make the Test123 class compile, you must add at least one constructor explicitly and use a throws clause to specify
that it may throw CException .
 
Search WWH ::




Custom Search