Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
Code that fails to honor the Catch or Specify Requirement will not compile.
Not all exceptions are subject to the Catch or Specify Requirement. To understand why, we need to look at the three basic categories of exceptions, only one of which is subject to the Requirement.
The Three Kinds of Exceptions
The first kind of exception is the checked exception
.
Checked exceptions are subject to the Catch or Specify Requirement
. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
The second kind of exception is the error
. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.
The third kind of exception is the runtime exception
.
Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.
Errors and runtime exceptions are collectively known as unchecked exceptions
.
unchecked exception 也可以被catch,只要match就行,也可以被throws, but we don’t have to do that: https://stackoverflow.com/questions/8104407/cant-java-unchecked-exceptions-be-handled-using-try-catch-block
Better Understanding on Checked Vs. Unchecked Exceptions
1 | try |
finally
block it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
The try-with-resources
statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
, can be used as a resource.
1 | static String readFirstLineFromFile(String path) throws IOException |
Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Throw exception
declare throws exception for method
1 | public void writeList() throws IOException {} |
throw an exception
1 | public void test() { |
Create custom exception: https://www.baeldung.com/java-new-custom-exception
1 | // create custom exception |