Java exceptions
Java exceptions fall into two categories, checked exceptions and runtime exceptions, and checked exceptions are exceptions that can be handled during the compilation phase.
Differences and connections between checked anomalies and runtime anomalies
- Checked exceptions are exceptions that can be handled, and the checked exception must be handled explicitly in the program, and if not processed, the compilation will be error-free. and the runtime exception can not be explicitly processed;
- Are exception subclasses, inherited RuntimeException is runtime exception, the other is checked exception.
Common exception classes
Several common run-time exception runtimeexception are listed:
- Indexoutofboundexception: Array out-of-bounds exception;
- NullPointerException: null pointer exception;
- ClassCastException: class conversion exception;
- NumberFormatException: Numeric format exception;
- ArithmeticException: Operation exception.
List several non-runtime exceptions (checked exceptions):
- Sqlexception:sql Abnormal;
- Ioexception:io Abnormal;
- FileNotFoundException: File cannot find exception, is IOException subclass;
- Interruptedexception: Interrupt exception, generally used in multithreaded programming;
- ClassNotFoundException: Class not found.
Error errors
Error errors generally refer to problems related to virtual machines, such as system crashes, virtual machine errors, dynamic link failures, and so on, which can be unrecoverable or not captured and will result in an application outage. Often applications cannot handle these errors, so you should not attempt to use catch to catch an Error object in your program. There is also no need to throws the error object when the method is defined.
Use of checked exceptions
As mentioned earlier, checked must be handled explicitly, or compile an error, such as declaring a file input stream:
new FileInputStream("test.md");
This code compilation will error
Unhandled exception type FileNotFoundException
It must therefore be handled explicitly, and there are generally two ways to handle checked exceptions:
- If you know how to handle it, it's best to use try...catch ... Block handling:
java //Checked异常必须被显式处理 try { FileInputStream fis = new FileInputStream("test.md"); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("文件不存在!"); }
- If you do not know how to handle it, it is thrown in the method and handled by the caller at the top level:
"' Java
public static void Main (string[] args) throws FileNotFoundException {
//Checked异常必须被显式处理//在main方法中抛出异常,交给JVM处理,JVM对异常的处理办法就是打印跟踪栈信息,并终止程序运行FileInputStream fis = new FileInputStream("test.md");
}
```
Throwing exceptions by using the throw self
Sometimes, depending on the business needs, we will throw an exception in the program itself, such as if the content of the read file is empty, we think this is an exception, we can use throw to actively throw an exception, and catch it by catching:
//使用throw主动抛出异常try { new FileInputStream("test.md"); if(fis.read0) { thrownew IOException("空文件"); catch (IOException e) { e.printStackTrace();}
If the throw throws a runtime exception, then the program can use Try...catch ... Capture, or you can ignore it.
Exception chain Processing
In real enterprise applications, we tend not to expose the underlying anomalies to upper-level applications, such as not exposing SQL anomalies to the user interface. One is that for users, it is not helpful to see the SQL exception, and the second is that it is unsafe for malicious users to expose the underlying exception.
So how do you block the underlying exception? The usual practice is that the program catches the original exception, then throws a new business exception, and the new business exception contains the user's prompt information, which is treated as an exception translation. The following shows how a program that creates a user masks the underlying exception:
//演示异常链,创建用户publicvoidcreateSubscriber(intthrows BusinessException { try { //创建用户的逻辑...... }catch(Exception e){ //处理并保存原始异常... //抛出新的业务异常 thrownewBusinessException("用户创建失败"); }}
You can see that the program hides the original exception and provides only the necessary exception hints to ensure that the underlying exception does not extend to the presentation layer, which conforms to the object's encapsulation principle.
This captures an exception and then throws another exception, and saves the original exception information, which is a typical chained process that is called the chain of responsibility pattern in design mode.
Several suggestions for using exceptions
We use exceptions to achieve several goals:
- Minimize the confusion of program code;
- Capture and retain diagnostic information;
- inform the appropriate personnel;
- The appropriate way to end the abnormal activity.
To address these goals, we should:
- do not overuse and rely on it: exceptions are convenient, but do not use exception handling for normal logical handling, such as
//原始代码if100){ Sysotem.out.println("文件过大,请重新上传"); continue;}//改成使用异常 if100){ thrownew Exception("文件过大,请重新上传");}//这样做,很明显不负责任。
- do not write a lot of code in the try: this may increase the difficulty of the analysis of the exception, and a large number of code may require a large number of catch to catch different exceptions;
- avoid catching all types of exceptions by using catch: for
catch(Throwable t)
example catch(Exception e)
, if you use the same logic for all exceptions, you have to write many if statements to deal with different situations, and this kind of capture can be error, runtime, etc. may cause the program to terminate the exception capture, thus "suppress" the exception, some key anomalies may be silently ignored;
- do not ignore the caught exception:catch should do something useful, do not empty or just print the exception, the catch block is empty is cheat, the program error, everyone can not see any exception, but the program may have been broken! When an exception is caught, it is either handled, either throws a new exception, throws up and handles the exception in the appropriate place.
Reference:
"Crazy Java Handout"
Introduction to Java Exceptions