如何在String数组为null时抛出异常?Truck构造器校验实现
在Truck构造器中校验materials数组是否为null的实现方式
问题描述
我希望在通过构造器创建Truck实例时,若String数组参数materials为null,则抛出新的TruckException。请问在if语句中应如何校验该数组是否为null?相关代码如下:
{ private String[] materials = new String[5]; private long permit = 0; private String company = ""; public Truck(String[] materials, long permit, String company, String ownerName, String ownerAddress, String brand, String model, String licencePlate, float value) throws TruckException, VehicleException { super(ownerName, ownerAddress, brand, model, licencePlate, value); setMaterials(materials); //on ne fait pas setMaterial(this.materials) car setMaterials modifie this.materials if(materials.length == 0 || materials.length>5 // ||???) //this if statement throw new TruckException("materials"); this.company = company; if(company.equals("")) throw new VehicleException("company"); //rest of code... }
解决方案
要实现null校验,必须先判断数组是否为null——直接访问null数组的length属性会触发NullPointerException。利用逻辑或(||)的短路特性(只要前面的条件为真,后面的条件就不会执行),可以避免空指针异常。
修改后的if语句如下:
if(materials == null || materials.length == 0 || materials.length > 5) throw new TruckException("materials");
额外优化建议
你当前代码先调用setMaterials(materials)再做参数校验,如果setMaterials方法未处理null情况,会在校验前触发空指针异常。建议将校验逻辑提前到setMaterials调用之前,确保参数合法后再执行赋值操作,调整后的完整代码片段:
public Truck(String[] materials, long permit, String company, String ownerName, String ownerAddress, String brand, String model, String licencePlate, float value) throws TruckException, VehicleException { super(ownerName, ownerAddress, brand, model, licencePlate, value); // 先执行参数合法性校验 if(materials == null || materials.length == 0 || materials.length > 5) throw new TruckException("materials"); setMaterials(materials); // 参数合法后再赋值 this.company = company; if(company.equals("")) throw new VehicleException("company"); // rest of code... }
内容的提问来源于stack exchange,提问作者Nicholas Spektor
相关产品推荐
相关产品推荐

