Check knowledge points
This question mainly involves the following knowledge points:
-
Java exception handling mechanism:understand
Throwable
、Exception
andError
The inheritance relationship and its role in exception handling. -
Exception classification:master
Checked Exception
andUnchecked Exception
The difference, andError
Features. - Exception handling practice: How to correctly handle exceptions in the code and avoid common error handling methods.
Answer description
Exception
andError
AllThrowable
The only subclass ofThrowable
Objects of types can be caught by throw or catch, but they play different roles in Java exception handling mechanism.
ExceptionIt indicates that exceptions that may be encountered during normal operation of the program, which can usually be captured and processed through code.Exception
It is divided into two categories:
-
Checked Exception(Compiled-time exception): The throw must be explicitly caught or declared in the code, e.g.
IOException
、SQLException
。 -
Unchecked Exception(Runtime exception): Usually caused by program logic errors, e.g.
NullPointerException
、ArrayIndexOutOfBoundsException
。
ErrorIndicates a serious problem that the program cannot handle, usually caused by system or JVM errors, e.g.OutOfMemoryError
、*Error
。Error
Capture is usually not required, because programs tend to be unable to recover in this case.
Definition and source
-
Exception
: Problems that may arise during the program's running and can usually be captured and processed. -
Error
: JVM-level problems are usually not recoverable, and developers do not need to actively capture them.
Is it recoverable
-
Exception
: Recoverable in most cases through remedial measures. -
Error
: The vast majority of them are unrecoverable, which usually leads to program crashes.
/** * Example of comparison of Exception and Error */ public class ExceptionAndErrorDemo { public static void main(String[] args) { // Checked Exception example try { (1000); // InterruptedException will be thrown } catch (InterruptedException e) { ("Catched Checked Exception: " + ()); } // Unchecked Exception example try { int result = 10 / 0; // ArithmeticException will be thrown } catch (ArithmeticException e) { ("Catched Unchecked Exception: " + ()); } // Error example (non-treated) try { int[] arr = new int[Integer.MAX_VALUE]; // May cause OutOfMemoryError } catch (OutOfMemoryError e) { ("Catched Error (not recommended): " + ()); } } }
Image metaphor
Imagine you are driving up the mountain:
-
Exception: The car suddenly broke down, but you brought the toolbox and you can continue to go on the road after repairing it (
Exception
Captured, the program recovers from the exception, continues to run). - Checked Exception: The car broke down and you don’t know how to repair it, so you call the repair shop and tell them the specific problem (throw an exception and handle it to a higher level).
- Unchecked Exception: The car broke down, but you found that it was because you forgot to refuel (logical errors can be avoided by encoding).
-
Error: The mountain suddenly collapsed and the car was buried. Can you still repair it? (
Error
: The program running environment enters an unrecoverable state).
Knowledge expansion
1. Common subclasses of Error
-
OutOfMemoryError
: Insufficient memory, new objects cannot be allocated. -
*Error
: Recursive call causes stack overflow. -
NoClassDefFoundError
: The class is visible at compile time, but not found at runtime.
2. Catch specific exceptions
Avoid catching common exceptionsException
, instead, capture specific exception types, which can provide more context information. This allows for clearer expression of the intent of the code and avoids catching exceptions that are not intended to be processed.
try { (1000); // InterruptedException may be thrown} catch (InterruptedException e) { // Capture a specific InterruptedException ("Thread interrupted: " + ()); }
3. Do not swallow any abnormalities
A raw swallowing exception means that no processing is done after the exception is caught, which will cause the program to end in an uncontrollable way in subsequent code. The correct way is to throw or log the exception to the log.
try { // Code that may throw exceptions} catch (IOException e) { // Do not swallow raw abnormalities, record them in the log ("IO exception occurred", e); // Or throw a new exception throw new RuntimeException("IO exception", e); }
4. Custom exceptions
In some cases, we may need to customize the exception. When customizing exceptions, the following points need to be considered:
-
Whether it needs to be defined as Checked Exception: If the exception can be restored through code, it can be defined as
Checked Exception
。 - Avoid including sensitive information: Avoid including sensitive data in exception information to prevent potential security issues.
/** * Custom exception example */ public class CustomException extends Exception { public CustomException(String message) { super(message); } } public class CustomExceptionExample { public static void main(String[] args) { try { throw new CustomException("This is a custom exception"); } catch (CustomException e) { ("Catched custom exception: " + ()); } } }
5. Use try-with-resources
Java 7 has introducedtry-with-resources
Syntax, can be automatically closed and implementedAutoCloseable
Interface resources simplify resource management code.
/** * Use try-with-resources to process resources */ public class TryWithResourcesDemo { public static void main(String[] args) { try ( reader = new ("")) { int data; while ((data = ()) != -1) { ((char) data); } } catch ( e) { ("File reading failed:" + ()); } } }
6. Throw early, catch late principle
- Throw early: Throw exceptions as soon as possible when problems are found to avoid the spread of problems.
- Catch late: Catch exceptions at the appropriate level, usually at the level where exceptions can be handled.
public void processFile(String filePath) throws IOException { if (filePath == null) { throw new IllegalArgumentException("File path cannot be empty"); // Throw early } try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { // Process files } // Catch late, handle exceptions on the caller}
This is the end of this article about the difference between Exception and Error in Java. For more information about the difference between Exception and Error, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!