Home > Java > Java Tutorial > body text

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

高洛峰
Release: 2017-01-18 14:56:29
Original
2408 people have browsed it

throw throws an exception in a more direct way:

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

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);
     }
   }
  
 }
Copy after login

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

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!