Exceptions of advanced features of Vernacular Java
The content of this article belongs to the scope of basic knowledge research. Do not think that the exceptional knowledge can be mastered after reading this article. Remember: I am not familiar with source code reading, so it is difficult for you to know when to customize exceptions and when to throw exceptions.
Exception mechanism Overview
The exception mechanism refers to how the program handles errors. Specifically, the exception Mechanism provides a secure channel for program exit. When an error occurs, the execution process of the program changes, and the control of the program is transferred to the exception processor.
Exception Handling Process
When an exception is thrown in the program, the program jumps out of the Code that causes the exception in the program. The Java virtual machine detects catch blocks that match the try keyword to handle the exception. if an exception is found, the control is handed over to the Code in the catch block, and then the program continues to be executed. The code with exceptions in the try block will not be re-executed. If no catch block is found to handle the exception, the current thread is aborted when all finally block code is executed and the ThreadGroup uncaughtException method of the current thread is called.
Let's talk about the benefits of exception handling technology.
Exception Handling is more advantageous than traditional error management technologies. Exception Handling can separate error code from normal code. In traditional programming technologies, error detection, reporting, and processing code are often complicated and complex as the processing logic of programs becomes abnormal.
Abnormal Structure
Exception inheritance structure: Throwable is the base class. Error and Exception inherit Throwable, RuntimeException, and IOException. Error, RuntimeException, and its subclass become unchecked, and other exceptions become checked ).
For the readFile () method for reading files, the pseudo code of its processing logic is as follows.
ReadFile {
Open the file;
Obtain the object length;
Allocate enough memory space.
Read the file content to the memory.
Close the file.
}
Although the above logic is simple, it ignores the possible error handling.
Pseudo code after exception handling technology is used
ReadFile {
Try {
Open the file;
Obtain the object length;
Allocate enough memory space.
Read the file content to the memory.
Close the file.
} Catch (File opening failed ){
// Dosomething
}
Catch (failed to read all file beds ){
// Dosomething
}
Catch (failed to allocate memory space ){
// Dosomething
}
Catch (failed to read file content ){
// Dosomething
}
Catch (failed to close the file ){
// Dosomething
}
}
When exception handling technology is used, you should write normal code and error handling code in different places. Although the security exception handling technology does not reduce the workload for programmers to handle errors, it can help programmers organize the error handling work more effectively.
Exception Handling Mechanism:
1. Capture exceptions
2. The declaration throws an exception.
Java. lang. ExceptionClass is the direct or indirect parent class for all exceptions in Java. That is, the Exception class is the root class of all exceptions.
For example:
Public class ExceptionTest
{
Public static void main (String [] args)
{
Int a = 3;
Int B = 0;
Int c = a/B;
System. out. println (c );
}
}
After compilation is passed, the execution result is as follows:
Exception inthread "main"Java. lang. ArithmeticException:/By zero
At com. learnjava. exception. ExceptionTest. main (Predictiontest. java: 9)
Because the divisor is 0, an arithmetic exception is thrown.
Common exceptions include:Null Pointer exception
Java. lang. NullPointerExceptionIt is a null pointer exception. The cause of this exception is that a reference is null, but a method of it is called. This exception occurs.
Exceptions in Java fall into two categories:
1.Checked Exception(NonRuntimeException)
2.Unchecked Exception(Runtime Exception)
Runtime exception
RuntimeExceptionA class is a subclass of the Exception class. It is called a runtime Exception. All runtime exceptions in Java are directly or indirectly inherited from the RuntimeException class.
In Java, any Exception that inherits from the Exception rather than the RuntimeException class isNon-runtime exception.
General Structure of Exception Handling
Try
{
// Code that may cause exceptions
// If an exception occurs, the code after the exception will not be executed
}
Catch (Exception e)
{
// Exception Handling Code
}
Finally
{
// The finally statement block will be executed no matter whether an exception occurs.
}
For example, the Division operation code at the beginning of this article, after adding exception handling:
Public class ExceptionTest
{
Public static void main (String [] args)
{
Int c = 0;
Try
{
Int a = 3;
Int B = 0;
// This code has encountered an exception.
C = a/B;
// The code after the exception is not executed
System. out. println ("HelloWorld ");
}
Catch (ArithmeticException e)
{
E. printStackTrace ();
}
Finally
{
// The finally statement block will be executed no matter whether an exception occurs.
System. out. println ("Welcome ");
}
System. out. println (c );
// When B is 0, an exception occurs. The output value is the initial value 0 of c.
}
}
Multiple catch
A try can be followed by multiple catch entries, but no matter how many catch entries,At most one catch block can be executed.
Exception Handling Method
ForNon-runtime exception (checkedexception ),It must be processed; otherwise it cannot be compiled.
There are two processing methods:
1. Use try... catch... finally to capture;
2. Write it after the method statement that generates the exceptionThrows an Exception type, Such as throws Exception, throws the Exception to the external layer.
For handling non-running exceptions, see the code example:
Method 1: capture exceptions
Public class ExceptionTest2
{
Public void method () throwsException // throws an exception and is handled by the method that calls this method. If the main method throws an exception, it is handed over to the Java Virtual Machine for processing.
{
System. out. println ("HelloWorld ");
// Throw an exception
Throw new Exception ();
}
Public static void main (String [] args)
{
ExceptionTest2 test = new ExceptionTest2 ();
Try
{
Test. method ();
}
Catch (Exception e)
{
E. printStackTrace ();
}
Finally
{
System. out. println ("Welcome ");
}
}
}
Method 2: continue to throw an exception
Public class ExceptionTest2
{
Public void method () throwsException // throws an exception and is handled by the method that calls this method. If the main method throws an exception, it is handed over to the Java Virtual Machine for processing.
{
System. out. println ("HelloWorld ");
// Throw an exception
Throw new Exception ();
}
Public static void main (String [] args) throwsException // select the main method to continue throwing an exception
{
ExceptionTest2 test = new ExceptionTest2 ();
Test. method (); // The main method must handle the exception.
// Execution result:
// Hello World
// Exception in thread "main" java. lang. Exception
// Atcom. learnjava. exception. ExceptionTest2.method (ExceptionTest2.java: 10)
// Atcom. learnjava. exception. ExceptionTest2.main (ExceptionTest2.java: 17)
}
}
ForRuntimeexception ),It can be processed or not. We recommend that you do not handle running exceptions.
Custom exception
A custom Exception is usually a class that inherits the Exception class or its subclass. The Exception must be directly or indirectly inherited from the Exception class.
Normally, it is directly inherited from the Exception class,AverageDoes not inherit an exception class during a running.
Custom exceptions can be used to handle user logon errors and user input error prompts.
Examples of custom exceptions:
Customize an exception type:
Public class MyException extendsException
{
Public MyException ()
{
Super ();
}
Public MyException (String message)
{
Super (message );
}
}
An exception handling method:
Public class ExceptionTest4
{
Public void method (String str) throwsMyException
{
If (null = str)
{
Throw new MyException ("the input string parameter cannot be null! ");
}
Else
{
System. out. println (str );
}
}
Public static void main (String [] args) throwsMyException // Exception Handling Method 1, which is continuously thrown out
{
ExceptionTest4 test = new ExceptionTest4 ();
Test. method (null );
}
}
Another exception handling method:
Public class ExceptionTest4
{
Public void method (String str) throwsMyException
{
If (null = str)
{
Throw new MyException ("the input string parameter cannot be null! ");
}
Else
{
System. out. println (str );
}
}
Public static void main (String [] args)
{
// Exception Handling Method 2, using the try... catch statement
Try
{
ExceptionTest4 test = new ExceptionTest4 ();
Test. method (null );
}
Catch (MyException e)
{
E. printStackTrace ();
}
Finally
{
System. out. println ("program processing completed ");
}
}
}
As mentioned earlier,There can be multiple catch blocks to catch different exceptions. during actual execution, only one catch block can be entered..
The following example defines two types of custom exceptions:
Public class MyException extendsException
{
Public MyException ()
{
Super ();
}
Public MyException (String message)
{
Super (message );
}
}
Public class MyException2 extends Exception
{
Public MyException2 ()
{
Super ();
}
Public MyException2 (String message)
{
Super (message );
}
}
Public class ExceptionTest4
{
Public void method (String str) throwsMyException, MyException2
{
If (null = str)
{
Throw new MyException ("the input string parameter cannot be null! ");
}
Else if ("hello". equals (str ))
{
Throw new MyException2 ("the input string cannot be hello ");
}
Else
{
System. out. println (str );
}
}
Public static void main (String [] args)
{
// Exception Handling Method 2, using the try... catch statement
Try
{
ExceptionTest4 test = new ExceptionTest4 ();
Test. method (null );
}
Catch (mydomaintione)
{
System. out. println ("entering the MyException catch Block ");
E. printStackTrace ();
}
Catch (MyException2 e)
{
System. out. println ("entering MyException2 catch Block ");
E. printStackTrace ();
}
Finally
{
System. out. println ("program processing completed ");
}
}
}
We can use multiple catch blocks to capture exceptions.Place the catch Block of the parent type after the catch Block of the Child typeIn this way, the subsequent catch blocks may be executed. Otherwise, the Child-type catch blocks will never arrive, and the Java compiler will report an error.
If the exception types are independent, there is no requirement for their order.
After the above Code is modified, it is listed as follows:
Public class ExceptionTest4
{
Public void method (String str) throwsException // You can also declare an Exception, as long as the declared Exception can cover all thrown exceptions.
{
If (null = str)
{
Throw new MyException ("the input string parameter cannot be null! ");
}
Else if ("hello". equals (str ))
{
Throw new MyException2 ("the input string cannot be hello ");
}
Else
{
System. out. println (str );
}
}
Public static void main (String [] args)
{
// Exception Handling Method 2, using the try... catch statement
Try
{
ExceptionTest4 test = new ExceptionTest4 ();
Test. method (null );
}
Catch (MyException e)
{
System. out. println ("entering the MyException catch Block ");
E. printStackTrace ();
}
Catch (MyException2 e)
{
System. out. println ("entering MyException2 catch Block ");
E. printStackTrace ();
}
Catch (effectione)
{
// This code will not be executed even though it needs to be added, just for compilation success
System. out. println ("entering the MyException catch Block ");
E. printStackTrace ();
// If the first two catch blocks or one of them are removed, the catch block is entered when this exception occurs.
// Catch block matching follows the order from top to bottom, so if this block is placed at the beginning, all exceptions will be caught, and the subsequent blocks will never be executed. At this time, a compilation error will be prompted.
}
Finally
{
System. out. println ("program processing completed ");
}
}
}
Regular interview questions
Exit statement in try Block
Although this is not the case in actual development, the following situations are frequently asked about exceptions during the test interview:
Public class ExceptionTest5
{
Public void method ()
{
Try
{
System. out. println ("Enter try block ");
// Return;
// The finally block will be executed before returning
// Exit the VM
// System. exit (0 );
// Does not execute statements in the finally block and exits directly.
}
Catch (Exception e)
{
System. out. println ("exception occurred! ");
}
Finally
{
System. out. println ("entering finally block ");
}
System. out. println ("subsequent Code ");
}
Public static void main (String [] args)
{
ExceptionTest5 test = new ExceptionTest5 ();
Test. method ();
}
}
When a return statement exists in the try block, the statement in the finally block will be executed first, and then the method will return.
If the try block contains System. exit (0); statement, then the code in the finally block will not be executed, because System. exit (0) terminates the currently running Java virtual machine, and the program ends before the termination of the virtual machine.
Well, the above is my summary of java exceptions.