View Single Post
  #2 (permalink)  
Old 03-08-2008, 07:41 PM
hardwired hardwired is online now
Senior Member
 
Join Date: Jul 2007
Posts: 1,144
hardwired is on a distinguished road
Quote:
C:\jexp>javac factorytest.java
factorytest.java:3: unreported exception java.lang.Exception; must be caught or declared to be thrown
String mac = ComputerFactory.create(ComputerType.Mac);
^
1 error
Code:
public class FactoryTest { public static void main(String[] args) { // The ComputerFactory.create method declares // that it throws an Exception. So the caller // must be prepared to catch it. String mac = null; try { mac = ComputerFactory.create(ComputerType.Mac); } catch(Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); } System.out.println("mac = " + mac); } } final class ComputerFactory { public static String create(ComputerType type) throws Exception { switch(type) { case PC: return "new CompPC"; case Mac: return "new CompMac"; case Sparc: return "new CompSparc"; case Itanium: return "new CompItanium"; } throw new Exception("No such computer: " + type ); } } enum ComputerType { PC, Mac, Sparc, Itanium }
Reply With Quote