Maison  >  Article  >  Java  >  Java编程中使用throw关键字抛出异常的用法简介

Java编程中使用throw关键字抛出异常的用法简介

高洛峰
高洛峰original
2017-01-18 14:56:292490parcourir

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关键字抛出异常的用法简介

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()方法抛出的异常");//输出异常信息
}
}
}

更多Java编程中使用throw关键字抛出异常的用法简介相关文章请关注PHP中文网!


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn