/*
*自定义异常类
*/
public class UnsupportedShapeException extends Exception{
private static final long serialVersionUID = 1L;
public UnsupportedShapeException(){
System.out.println("我的自定义异常类");
}
}
/*
*使用
*/
public class ShapeFactory {
public static Shape createShape(String shape) throws UnsupportedShapeException{
if(shape.equalsIgnoreCase("circle")){
System.out.println("producing circle....");
return new Circle();
}else if(shape.equalsIgnoreCase("rectangle")){
System.out.println("producing rectangle....");
return new Rectangle();
}else if(shape.equalsIgnoreCase("triangle")){
System.out.println("producing triangle....");
return new Triangle();
}else{
throw new UnsupportedShapeException();
}
}
}
本文介绍了一个自定义异常类UnsupportedShapeException及其在ShapeFactory类中的应用。当ShapeFactory尝试创建不支持的形状时,会抛出自定义异常。示例中展示了如何为circle、rectangle和triangle创建实例,而其他形状则触发异常。
2178

被折叠的 条评论
为什么被折叠?



