Wednesday, February 14, 2007

Custom Exceptions


Till now we have seen why we need Exceptions and how to manage code that could throw Exceptions. We still have not learned how to throw our own Exceptions. Let us first understand the code below.
























01 public class DocToPdfConverter {
02   public void convert(String src, String des) {
03     Document doc = readDoc(src);
04     writePdf(doc, des);
05   }
06
07   private Document readDoc(String srcPath) {
08   //read the source file and verify format
09   //if format is incorrect then throw an Exception
10   }
11
12   private void writePdf(Document doc, String des) {
13     //convert the document into pdf
14   }
15 }




Java2html


























01 public class DocToPdfConverter {
02   public void convert(String src, String des) {
03     Document doc = null;
04     try {
05       Document doc = readDoc(src);
06       writePdf(doc, des);
07     } catch(InvalidFormatException ife) {
08     //print error msg for user
09     } catch(IOException ioe) {
10     //print error msg for user
11     }
12   }
13
14   private Document readDoc(String srcPath) throws InvalidFormatException, IOException {
15     if(!verifyFormat(srcPath)) {
16       throw new InvalidFormatException("The file " + srcPath + "is not a valid word file");
17     }
18     Document document = convertDocToOM(srcPath);
19     return document;
20   }
21
22   private void writePdf(Document doc, String des) {
23     //convert the document into pdf
24   }
25
26   private Document convertDocToOM(String srcPath) {
27     //code
28   }
29 }




Java2html

























1 public class InvalidFormatException extends Exception {
2   public InvalidFormatException() {
3     super();
4   }
5
6   public InvalidFormatException(String msg) {
7     super(msg);
8     }
9 }




Java2html


Notes: This text was originally posted on my previous blog at http://www.adaptivelearningonline.net

No comments: