在练习的时候,我总是无法分清何时用throw抛出异常
有的时候只需要System.out.println("..."); return; 就可以完成异常的指出
但是有时候老师写代码的时候会使用以上两种方法的任意一种
折让我很迷惑
到底什么时候使用哪种异常报错呢?
比如说:
当这个方法中是:
public void list(){ if (first.getNext()==null){ System.out.println("栈空"); return; } }
这时候,方法声明的时候是 void ,返回值为空,这时候用return 或者 throw 都可以
但是当这种情况出现时:
public int throwTest(){ }
其中返回值是 int,这时候如果想表示异常,那么可以用return + 一个 int 类型
或者直接:
throw new RuntimeException("..");
当使用了这个语句的时候,不需要加return 了!
再举个例子
public int pop() { if (isEmpty()) { throw new RuntimeException("栈空"); } int value = stack[top]; top--; return value; }
这时候抛出异常,显示的是:
Welcome!
push:输入一个数
pop:弹出一个数
list:查看列表
exit:退出
pop
栈空
但是如果将:throw new RuntimeException("栈空");
改成:System.out.println("栈空"); return;
那么显示的就会是:
栈空 Index -1 out of bounds for length 5
会出现这个以上这个多余的显示!
posted on
浙公网安备 33010602011771号