7.1使用异常而非返回码
1.返回状态码
如果函数出错,则返回特定的状态码
这样shutdown() 方法内部可能也发生错误,故不可取
public static int shutDown(){
...
if(go wrong){
return -1;
}
}
public static void main(String[] args){
if(shutdown()!= -1){
.....
}
}
2.使用 try-catch-finally语句
try{
事务代码(发生错误则结束)
} catch{
事务代码报错,在catch中继续执行
}
例如
随意命名一个文件(不存在)
- try 部分报错
- 直接跳到catch 部分
- 最后执行finally
@Test
public void testTry(){
try {
File file=new File("C:\\33\33\\2.txt");
FileInputStream fileInputStream=new FileInputStream(file);
System.out.println("读取输入流没报错" );
} catch (Exception e){
e.printStackTrace();
} finally {
System.out.println("执行 finally 语句" );
}
System.out.println("执行完了try catch语句" );
}
/** output
java.io.FileNotFoundException: C:\33\2.txt (文件名、目录名或卷标语法不正确。)
.... (报错语句)
执行 finally 语句
.... (系统输出语句)
执行完了try catch语句
7.7 别返回null值
NullPointException 空指针异常,我是经常遇到
调用的值是null,这时候控制台就报错了
这时候就要加null判断了
当null判断过多,代码就显得臃肿了
所以想办法不要返回null
@Test
public void testReturnNull(){
if(getResult()!=null){
System.out.println("不为空");
} else{
System.out.println("为空");
}
}
public static Integer getResult(){
return null;
}