Home > Java > javaTutorial > body text

Briefly understand the methods of throwing exceptions in Java programming

高洛峰
Release: 2017-01-18 14:58:43
Original
1585 people have browsed it

Any Java code can throw exceptions, such as code written by yourself, code from the Java development environment package, or the Java runtime system. Anyone can throw an exception through Java's throw statement. Any exception thrown from a method must use a throws clause.

1. throws throws exceptions

If a method may throw an exception, but does not have the ability to handle such exceptions, you can use the throws clause at the method declaration to declare that an exception is thrown. For example, a car may malfunction while it is running. The car itself cannot handle the malfunction, so let the driver handle it.

The throws statement is used when defining a method to declare the exception type that the method will throw. If the exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be separated by commas. The syntax format of the throws statement is:

methodname throws Exception1,Exception2,..,ExceptionN
{
}
throws Exception1,Exception2,…,ExceptionN after the method name is the declaration to throw exception list. When a method throws an exception from the exception list, the method will not handle exceptions of these types and their subclass types, but will be thrown to the method that calls the method for handling. For example:

import java.lang.Exception; 
public class TestException { 
  static void pop() throws NegativeArraySizeException { 
    // 定义方法并抛出NegativeArraySizeException异常 
    int[] arr = new int[-3]; // 创建数组 
  } 
   
  public static void main(String[] args) { // 主方法 
    try { // try语句处理异常信息 
      pop(); // 调用pop()方法 
    } catch (NegativeArraySizeException e) { 
      System.out.println("pop()方法抛出的异常");// 输出异常信息 
    } 
  } 
   
}
Copy after login

After using the throws keyword to throw an exception to the caller, if the caller does not want to handle the exception, it can continue to throw it upward, but in the end there must be a caller who can handle the exception.

The pop method does not handle the exception NegativeArraySizeException, but is handled by the main function.

Throws rules for throwing exceptions:

1) If it is an unchecked exception (unchecked exception), that is, Error, RuntimeException or their subclasses, you can declare it without using the throws keyword The exception to be thrown will still pass smoothly during compilation, but will be thrown by the system at runtime.

2) Any checked exceptions that the method can throw must be declared. That is, if a method may have a checkable exception, either use a try-catch statement to catch it, or use a throws clause statement to throw it, otherwise it will cause a compilation error

3) Only when an exception is thrown, Only the caller of this method must handle or rethrow the exception. When the caller of the method is unable to handle the exception, it should continue to throw it instead of swallowing the exception.

4) The calling method must follow the handling and declaration rules of any checkable exception. If you override a method, you cannot declare a different exception than the overridden method. Any exception declared must be of the same class or subclass as the exception declared by the overridden method.

For example:

The basis for judging whether an exception may occur in a method is as follows:

1) There is a throw statement in the method. For example, the catch code block of the method7() method above has a throw statement.

2) Other methods are called, and other methods declare to throw some kind of exception using the throws clause. For example, the method3() method calls the method1() method, and the method1() method declares to throw IOException. Therefore, an IOException may occur in the method3() method.

2. Use throw to throw exceptions

throw always appears in the function body and is used to throw an exception of type Throwable. The program will terminate immediately after the throw statement, and the statements following it cannot be executed. Then it will search from the inside out for a try block that contains a matching catch clause in all try blocks containing it (possibly in the upper-layer calling function).

We know that exceptions are instance objects of the exception class. We can create instance objects of the exception class and throw them through the throw statement. The syntax format of this statement is

throw new exceptionname;
Copy after login

For example, throwing an exception object of the IOException class:

throw new IOException;
Copy after login

It should be noted that throw throws can only be instance objects of the throwable class Throwable or its subclasses. The following operation is wrong:

throw new String(“exception”)
Copy after login

This is because String is not a subclass of the Throwable class.

If a checked exception is thrown, the exception type that the method may throw should also be declared in the method header. The caller of this method must also check to handle the thrown exception.

If all methods throw the obtained exceptions layer by layer, the JVM will eventually handle it. The processing is also very simple, which is to print the exception message and stack information. If an Error or RuntimeException is thrown, the caller of the method can choose to handle the exception.

package Test;
import java.lang.Exception;
public class TestException {
  static int quotient(int x, int y) throws MyException { // 定义方法抛出异常
    if (y < 0) { // 判断参数是否小于0
      throw new MyException("除数不能是负数"); // 异常信息
    }
    return x/y; // 返回值
  }
  public static void main(String args[]) { // 主方法
    int a =3;
    int b =0; 
    try { // try语句包含可能发生异常的语句
      int result = quotient(a, b); // 调用方法quotient()
    } catch (MyException e) { // 处理自定义异常
      System.out.println(e.getMessage()); // 输出异常信息
    } catch (ArithmeticException e) { // 处理ArithmeticException异常
      System.out.println("除数不能为0"); // 输出提示信息
    } catch (Exception e) { // 处理其他异常
      System.out.println("程序发生了其他的异常"); // 输出提示信息
    }
  }
   
}
class MyException extends Exception { // 创建自定义异常类
  String message; // 定义String类型变量
  public MyException(String ErrorMessagr) { // 父类方法
    message = ErrorMessagr;
  }
   
  public String getMessage() { // 覆盖getMessage()方法
    return message;
  }
}
Copy after login

For more articles related to simply understanding the methods of throwing 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!