throw抛出异常的⽅式⽐较直接:
if(age < 0){
throw new MyException(\"年龄不能为负数!\");}
来看⼀个例⼦:
package Test;
public class Test2 {
public static void main(String[] args) { String s = \"abc\"; if(s.equals(\"abc\")) {
throw new NumberFormatException(); } else {
System.out.println(s); } } }
运⾏结果如下:
java中可以对⼀个⽅法在定义时就进⾏异常的声明,⽽后在实现时可以利⽤throw具体的抛出异常。
ppublic class Shoot { 创建类
static void pop() throws NegativeArraySizeException {
//定义⽅法并抛出NegativeArraySizeException异常
int [] arr = new int[-3];//创建数组}
public static void main(String[] args) {//主⽅法try {
pop(); //调⽤pop()⽅法
} catch (NegativeArraySizeException e) {
System.out.println(\"pop()⽅法抛出的异常\");//输出异常信息}}}
因篇幅问题不能全部显示,请点此查看更多更全内容