Java Learning Journey – exceptions
Concept: Java has an exception handling mechanism to handle unexpected events that may occur during program execution, which greatly improves program robustness
Throwable and subclasses thereof
Throwable has two subclasses Error and Exception:
- Error: There are VirtualMachineError, OutOfMemoryError, ThreadDeath(thread deadlock)
- Exception: contains two parts: check Exception and non-check Exception:
- Check exceptions include IOException (IO exception) and SQLException (SQL exception). When this type of exception is thrown, the compiler will force processing
- There are four types of non-checked exceptions, runtimeExceptions, and when they are thrown,The compiler does not mandate processing(If a RuntimeException occurs, it must be your fault, so you should avoid NullPointerException by checking for NULL before using a variable; Check if array subscripts are out of bounds before using arrays) :
- NullPointerException
- ArrayIndexOutOfBoundsException (array subscript crossing the line)
- ArithmeticException
- ClassCastException(type conversion exception)
try-catch-finally
This is a combination of keywords. The try {} code block contains code that may be abnormal. If an exception object is found that matches the type of the catch, the code block inside the catch{} can have multiple catches. Finally {} contains code that executes whether or not an exception object is thrown.
What if you want to not execute a statement in finally?
There are two methods: system.exit (1); And return, but return is special. No matter where a return is, finally is executed before return.
The main points of
- The last catch is best done with Exception, so that the Exception type you missed can’t be caught
- When handling exceptions, it depends on the business logic required
- Try to use the finally block to release occupied resources to make it more logical
Throws and throw
Through these two keywords to throw an exception, to external capture, thus processing. You can do “whoever calls this method, handles it” instead of calling it yourself, discovering the exception yourself, and handling it yourself.
public static void main(String args) {
try {
int result = test(a); System.out.println(The quotient of one and TWE is: + result);
} catch(InputMismatchException e){
System.out.println("Input format error");
} catch(ArithmeticException h){
System.out.println("What kind of anomaly is that?");
}catch (Exception a ){
System.out.println("What is it?"); }}Throws Exception * @return * @throws Exception */
public static int test(a)throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("------START-------");
System.out.print("Enter the first number one:");
int one =input.nextInt(a); System.out.print("Enter the second number two:");
int two = input.nextInt(a); System.out.println("------- operation completed ------");
return one/two;
}
Copy the code
Self-throwing and self-connecting can also be:
public static int test(a)throws Exception {
try {Scanner input = new Scanner(System.in);
System.out.println("------START-------");
System.out.print("Enter the first number one:");
int one =input.nextInt(a); System.out.print("Enter the second number two:");
int two = input.nextInt(a); System.out.println("------- operation completed ------");
return one/two;
}catch(InputMismatchException e){
System.out.println("Input format error");
} catch(ArithmeticException h){
System.out.println("What kind of anomaly is that?");
}catch (Exception a ){
System.out.println("What is it?"); }}Copy the code
Is there any other way the compiler doesn’t alert the programmer to handle unchecked exceptions?
Throws Exception * @return * @throws Exception */
Copy the code
The annotation form above will display a special color in IDEA, which will automatically detect if there are exceptions in your method that need to be handled. This allows the programmer to hold the mouse over a method call a little longer to see what exceptions need to be handled. It is a way to remind the programmer that there are no omissions in programming.
What if a subclass overrides a superclass method that declares a specific checking exception?
- First of all, a subclass can’t rewrite method statement the superclass method exception object in the parent class, such as the declaration in the parent class RuntimeException, subclasses of rewriting method can use ArrayIndexOutOfBoundsException (only can write more specific exception or run no exceptions).
- Second, a subclass method may not throw any exceptions if the parent method does not.
Create your own exception class
Describe your specific business needs by creating your own exception classes. Define a class that is derived from Exception, or a subclass of Exception. The custom class will have two constructors, one by default and one that contains the details (the toString method of the superclass Throwable returns a string containing the details), because Exception is also a subclass of Throwable.
Abnormal chain
You can continue to throw new exceptions in a catch to change the type of exception, and sometimes you don’t necessarily want to know the exact details of the failed exception, just whether something failed. Let’s say we were throwing the ArithmeticException in the previous code, so we’re going to wrap it instead of throwing another exception object, because throwing without wrapping would lose the original exception information. Throwable original = caughException. GetCause (); Throwable original = caughException.getCause(); Get the original exception.
public static void main(String args) {
try {
int result = test(a); System.out.println(The quotient of one and TWE is: + result);
} catch (ArithmeticException a ){
var a=new SerletException("database error");
e.initCause(original);
throwe; }}Copy the code
Or, just log an exception and rethrow it:
try{... }catch (Exception a ){
logger.log(level,maeeage,e)
throw e;
}
Copy the code
var
Var is a new Java10 feature that can temporarily replace keywords for various data types:
- Can only be used for local variables
- Must be initialized when declared
- Cannot be an argument to a method
At compile time, var is replaced by the assigned type.
What if a try statement throws an exception and the catch catches it, and the catch throws an exception to the caller of the method?
public static void main(String[] args) throws Exception {
try {
int result = test(a); System.out.println(The quotient of one and TWE is: + result);
} catch (ArithmeticException e){
System.out.println("An arithmetic exception has occurred.");
throw new Exception("A new mistake");
System.out.println("There's been another arithmetic anomaly.");// This is an error
} finally {
System.out.println("New error end"); }}Copy the code
Obviously, after a new error is thrown, the statement following the catch will not continue.
try-with-Resources
It seems that the try-with-resources statement is now more common than the finally clause, which features the ability to omit the finally clause and automatically call the system.in.closa () method on exception and exit to achieve the effect of using the finally block. Try with Resources; try with Resources;
try(Resource res=...)
{
work with res
}
Copy the code
Another interesting thing is that if a try throws an exception at the same time as a close method throws an exception, boy, that’s interesting. At this point, try-with-resources will automatically suppress the close exception, and the exception of the try will be rethrown. You can also call up an exception from close by calling the getSuppressed method.
In short, if you need to use and close a resource, use try-with-resources