Custom exceptions.

From: Mark Framness (farmer_at_netnet.net)
Date: 01/31/04


Date: Fri, 30 Jan 2004 19:32:10 -0600

Greetings,

For a motivating project I am working on creating a simple report writer in
Java. Below I have a little class to test my ReportField class. The
constructor being used has the following signature:

============================================================
public ReportField(String fieldname, String fieldvalue, String breakvalue,
int outPosition) throws FieldException {...
============================================================

FieldException is a class which extends Exception.

The way I have the line which constructs fldPhone will cause an exception to
be thrown (valid application values for the third field are "LB", "PB" and
" ", i.e. "AA" is invalid).

Snippet #1 refuses to compile unless the whole thing is in a try block per
SNIPPET #2, which produces the desired behavior.

This tells me there is a big difference between exceptions thrown by the
java runtime system and those I create. If I create an exception must I
always put the calls which can throw that exception into try blocks? Or is
there a way I can get around this? This could possibly mean making huge try
blocks since the objects created in the try block are not visible outside
of the block.

I am just getting started in making a serious attempt to learn Java, it
probably shows!

Thanks

SNIPPET #1
================================================================
public class reportit {
   public static void main(String args[]) {

   ReportField fldPhone = new ReportField("Phone number", "555-5309", "AA",
1);
   ReportField fldLName = new ReportField("Last name", "Stardust", "LB", 2);
   ReportField fldFName = new ReportField("First name", "Ziggy", "NB", 3);
   fldPhone.basicOutput();
   fldLName.basicOutput();
   fldFName.basicOutput();
   }
}
================================================================

SNIPPET #2
================================================================
public class reportit {
   public static void main(String args[]) {
      try {
         ReportField fldPhone = new ReportField("Phone number", "555-5309",
"AA", 1);
         ReportField fldLName = new ReportField("Last name", "Stardust",
"LB", 2);
         ReportField fldFName = new ReportField("First name", "Ziggy", "NB",
3);
         fldPhone.basicOutput();
         fldLName.basicOutput();
         fldFName.basicOutput();
         } catch (FieldException fldexception) { fldexception.basicOutput();
}

    }
}
================================================================

-- 
From: Mark A Framness <farmer@netnet.net>
http: http://netnet.net/~farmer/index.html
With all of thy getting, get understanding!
Proverbs 4:7