In addition to using try...catch statements and try...catch...finally statements to handle exceptions, you can also use throws to handle exceptions.
In development, sometimes we don't have permission to handle the exception. We don't know how to handle the exception, or we don't want to handle the exception. In this case, we can throw the exception and let the caller handle it.
throws format for handling exceptions:
[Access permission modifier] Return value type method name (parameter list) [throws exception class name] {method body; [return return value];}
Things to note:
1) The exception handling method must not be thrown to the JVM for processing [main method].
2) If a method throws a compile-time exception, the caller must handle it.
3) If a method throws a runtime exception, it may or may not be handled. It is recommended to handle it to improve the security of the program.
4) Exceptions declared by methods overridden by subclasses cannot be expanded.
5) Throws indicates the possibility of an exception occurring, and multiple exception classes can be declared.
throw exception handling method:
Format: throw exception object;
Note : We can find that in fact, the functions of throw and throws are to throw exceptions to the caller or the virtual machine for processing, but the fundamental difference between the two is that throw throws an exception object, while throws declares an exception class.
The difference between throw and throws:
1) throw throws an exception object, and throws declares an exception class.
2) throw can only throw one object, and throws can declare multiple exception classes.
3) Throw indicates that an exception has occurred, and throws is the possibility of an exception.
4) Throw appears in the method body, and throws appears in the method declaration.