Home >Java >javaTutorial >How to use the Java keywords throw, throws, and Throwable
throw means "throw, throw, throw". Throw, Throws and Throwable are all used for exception handling.
Throwable is the top-level parent class of the exception handling branch in Java. The implementation of all other exception handling relies on Throwable
Open the official Java documentation ( Java8 version), find Throwable, its direct subclasses are Error and Exception.
#The characteristic of Error and Exception is that the Error exception program cannot handle it and can only be left to manual intervention to modify the code, such as stack overflow, heap overflow, etc.; while Exception exception It can be detected in advance and dealt with effectively.
Among Errors, common ones include stack overflow, heap overflow, etc.
For example, StackOverflowError
public class ErrorTest { public static void main(String[] args) { main(args); } }
Infinite recursion, executing this program will report a stack overflow exception.
Another example is the heap exception, OutOfMemoryError
public class ErrorTest { public static void main(String[] args) { Integer[] testArray = new Integer[1024*1024*1024]; } }
In Exception There are many exceptions that we are familiar with, such as NullPointerException (null pointer exception), ArrayIndexOutOfBoundsException (array subscript out of bounds), NumberFormatException (number formatting exception), etc.
public class ExceptionTest { public static void main(String[] args) { int[] testArray = null; System.out.println(testArray[0]); //空指针异常 } }
public class ExceptionTest { public static void main(String[] args) { int[] testArray = new int[3]; System.out.println(testArray[3]); //数组下标越界 } }
public class ExceptionTest { public static void main(String[] args) { String num = "abc"; System.out.println(Integer.parseInt(num)); //数字格式化异常 } }
throws is applied at the method declaration to indicate the types of exceptions that may occur when this method is executed. Once an exception occurs when the method is executed, an object of the exception class will be generated at the exception code. When this object meets the exception type after Throws, it will be thrown. There are two processes here. When there is an exception in the code
1. Generate an exception object;
2. throws captures this exception and throws the exception object
throws and try-catch-finally together are called two ways of exception handling.
try-catch-finally actively handles the exception when an exception occurs, so that the program can continue to execute; while throws catches the exception and throws the exception object upward without actually handling the exception.
The so-called throwing exception object upward is to hand over the exception object to the caller for processing. For example, method A calls method B, B throws an exception through throws, and A can choose to use try-catch-finally to handle it. Exceptions can also be thrown upward through throws until the exception is actually handled. If there is no way to handle exceptions, the exception object will eventually be thrown to the JVM, causing the program to stop running.
@Test public void throwsTest(){ //调用者解决抛出的异常 try{ formatChange("abc"); } catch (NumberFormatException e){ System.out.println("转换格式错误!"); } catch (Exception e){ System.out.println("出现错误"); } } private int formatChange(String str) throws NumberFormatException{ //出现异常向上抛出 return Integer.parseInt(str); }
——How to choose try-catch-finally or throws?
When there is an exception in a method that needs to be handled, in most cases, you can either choose try-catch-finally to handle the exception directly, or you can choose throws to throw the exception upward and leave it to the caller to handle. (When an exception is thrown at the end, there must be one party who actually handles the exception. How to deal with it? Let’s use try-catch-finally.) You are relatively free in choice. However, when the following two situations occur, you need to follow certain rules. (If you have anything to add, please point it out).
If the overridden method in the parent class does not use throws to throw an exception, the method overridden by the subclass cannot use throws to throw an exception, which means that this situation Must use try-catch-finally to handle.
In method A, several other methods are called successively. These methods are executed in a progressive relationship and many of them have exceptions that need to be handled. In this case, it is recommended Several called methods use throws to throw upward exceptions. In method A, try-catch-finally is used to handle these exceptions uniformly.
Regarding the first one, this is a stipulation that the exception thrown by the overridden method in the subclass using throws must not be greater than the exception thrown by the overridden method in the parent class. scope. For example, if method B in the parent class throws NullPointerException, then the overridden method B in the subclass cannot throw exceptions such as Exception that have a wider scope than NullPointerException; if the overridden method in the parent class does not throw If any exception occurs, the subclass cannot throw an exception.
Why? Show a piece of code.
//假设父类中的方法B抛出NullPointerException异常,子类中的方法B可以抛出Exception private void test(ParentClassTest parent){ try{ parent.B(); } catch(NullPointerException e){ System.out.println("出现了空指针异常"); } }
In this example, assuming that method B in the parent class throws NullPointerException, the overridden method B in the subclass can throw Exception. Then if the parameters passed into the test method are instantiated objects of the parent class, then there is no problem in calling the test method. If the parameter passed in is an instantiated object of the subclass, and then the method B rewritten by the subclass is called, an Exception may be thrown, and the try-catch structure cannot suppress this exception. This is obviously an error. Reasonable operation.
针对第二条,假设方法A中调用了方法C、D、E,这三个方法都有可能产生异常,且存在递进关系,也就是D、E执行需要C执行完成、E执行依赖C、D执行完成。那么就推荐在C、D、E中向上抛出异常,在方法A中集中处理。为什么?如果C、D、E都是向上抛出异常,而A使用try-catch-finally去处理这个异常,如果某个方法真的出现异常,则不再继续执行。而如果C、D、E都使用try-catch-finally直接解决掉异常,那么即使产生了异常,方法A也不会接收到异常的产生,那么还会接着往下执行,但是C出现了异常,再执行D、E没有任何意义。
如果在程序编写时有手动抛出异常的需求,则可以使用throw
throw使用在方法体内。与try-catch-finally和throws都不同,异常处理的两个阶段:1.遇到异常,生成异常对象;2.捕获到异常,进行抛出或处理。try-catch-finally和throws都处在第二个阶段,都是捕获到异常后的相关处理,一般使用系统根据异常类型自动生成的异常对象进行处理。而throw应用在第一阶段,手动地产生一个异常对象。
举一个例子,判断一个数值是否为非负数,如果为负数,则抛出异常。
class ThrowTest{ private int Number; public void judge(int num){ if(num>=0){ this.Number = num; } else{ throw new RuntimeException("传入参数为负数"); } } }
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); throwTest.judge(-100); }
成功抛出异常。
使用try-catch捕获一下异常。
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); try{ throwTest.judge(-100); } catch (RuntimeException e){ System.out.println(e.getMessage()); } }
如果把throw抛出的异常改为Exception,则直接报错,也就是不能编译。Exception包含两种异常:编译时异常和运行时异常,前者在编译前就要检查是否有可能产生编译时异常;后者是在编译后运行时才会判断的异常。而throw new Exception包含了编译时异常,需要显式处理掉这个异常,怎么处理?try-catch-finally或者throws
class ThrowTest{ private int Number; public void judge(int num) throws Exception{ if(num>=0){ this.Number = num; } else{ throw new Exception("传入参数为负数"); } } }
调用方也要随着进行更改。
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); try{ throwTest.judge(-100); } catch (RuntimeException e){ System.out.println(e.getMessage()); } catch (Exception e){ System.out.println(e.getMessage()); } }
——自定义异常类
throw还可以抛出自定义异常类。
自定义异常类的声明需要继承于现有的异常体系。
class MyException extends RuntimeException{ static final long serialVersionUID = -703489719076939L; //可以认为是一种标识 public MyException(){} public MyException(String message){ super(message); } }
此时我们可以抛出自定义的异常
class ThrowTest{ private int Number; public void judge(int num) throws MyException{ if(num>=0){ this.Number = num; } else{ throw new MyException("不能输入负数"); } } }
调用者修改
@Test public void test2(){ ThrowTest throwTest = new ThrowTest(); try{ throwTest.judge(-100); } catch (MyException e){ System.out.println(e.getMessage()); } }
The above is the detailed content of How to use the Java keywords throw, throws, and Throwable. For more information, please follow other related articles on the PHP Chinese website!