Home  >  Article  >  Java  >  An introduction to using the throw keyword to throw exceptions in Java programming

An introduction to using the throw keyword to throw exceptions in Java programming

高洛峰
高洛峰Original
2017-01-18 14:56:292545browse

throw throws an exception in a more direct way:

if(age < 0){
throw new MyException("年龄不能为负数!");
}

Let’s look at an example:

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);
     }
   }
  
 }

The running results are as follows:

An introduction to using the throw keyword to throw exceptions in Java programming

In Java, you can declare an exception when a method is defined, and then you can use throw to specifically throw an exception during implementation.

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

For more related articles about using the throw keyword to throw exceptions in Java programming, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn