The examples in this article describe the usage of Java exception handling. Share it with everyone for your reference. The specific analysis is as follows:
Java's exception handling mechanism can help us avoid or handle errors that may occur in the program, so that the program will not terminate unexpectedly when encountering some recoverable errors, but to handle these errors, which also makes us better at writing programs. There is no need to write a lot of code to check error conditions, which enhances the readability and logic of the code. In Java, an exception represents an incorrect entity object.
Exceptions can be divided into two categories; one is serious errors, such as hardware errors, insufficient memory, etc., which correspond to the Error class and its subclasses under the java.lang package. Usually this type of error program itself cannot be recovered and needs to interrupt the execution of the program; the other type is non-serious errors, such as the user inputting illegal data, dividing by 0, etc. They correspond to the Exception class and its exceptions in the java.lang package. Subclass, this kind of error can generally be recovered without affecting the operation of the program.
We can use try, catch, and finally keywords to catch exceptions.
1. try, catch
Put the statements that may cause exceptions in the try{} block, and then catch them in the catch{} statement block. Exception if divided by 0:
public class SimpleDemo { //Division operation public static int devision(int a,int b) { return a / b; } public static void main(String[] args) { try { //5 divided by 0 SimpleDemo.devision(5 ,0); System.out.println("Exception"); } catch (Exception e) { e.printStackTrace(); } System.out.println("Finish"); } }Execution result:
As you can see, Finish is printed, indicating that the program did not terminate due to a division by 0 error.
At the same time, we also found that the System.out.println statement under SimpleDemo.devision() where the exception occurred was not executed. Once an exception occurs, the program will jump out from the current execution position without executing the statements following the exception.
2. finally
The statements in the finally block will be executed regardless of whether an exception occurs.
Someone may ask, since the statements in the finally block will be executed regardless of whether an exception occurs, then what is the practical effect of this finally? Can't I write it directly outside without finally?
As in the above example, we add a return to the catch statement block:
public class SimpleDemo { //Division operation public static int division(int a,int b) { return a / b; } public static void main(String[] args) { try { //5 divided by 0 SimpleDemo.division(5 ,0); System.out.println("Exception"); } catch (Exception e) { e.printStackTrace(); return; //main function returns} finally { System.out.println("Finally"); } System.out.println("Finish"); } }At this time, the Finish outside the finally block is not printed, but the Finally inside the finally block is printed.
finally is very useful in actual development. For example, if we open a database and an exception occurs when reading and writing data in the database, then we should close the database connection and release the corresponding resources. At this time, it is most appropriate to write the code to release resources in the finally block.
But it should be noted that the finally block will not be executed in one case. If the program exits before executing the finally block, such as calling the System.exit() method, the finally block will not get a chance to execute.
3. Throw an exception
If an exception occurs in a method, but we do not want to handle the exception directly in the method, but want the caller of the method to handle it, we can use the throws keyword to declare this method to throw the exception. This is very common in the API functions provided by Sun. For example, the read method in java.io.Reader is declared to throw an IOException:
public int read(char[] cbuf) throws IOException
At this time, when we call the read method, we must put it in the try statement block to catch exceptions, otherwise the compiler will report an error and force us to catch exceptions.
Of course, if we really don't want to handle exceptions when calling read, we can also declare the method that calls the read method as throws IOException, so that the exception will be thrown again. If we declare an Exception in the main function, the exception information will eventually be captured and processed by the JVM, and the JVM's processing result is to print out the exception information and then terminate the program.
4. Exception handling structure
All exception classes are derived from the Exception class. This means that if we are not sure what type of exception will occur, we can directly declare an Exception object in catch to catch all exceptions of the Exception class and its subclasses. But pay attention to the order in which catch is written. If there are multiple catches after a try and the first catch declares an Exception object, then the exception will be handled directly by the first catch, and subsequent catches will not be able to catch this exception. This kind of error will generate an error during compilation. For example:
public class CatchDemo { //Division operation public static int division(int a,int b) { return a / b; } public static void main(String[] args) { try { CatchDemo.division(4,0); } catch (Exception e) { System.out.println("Exception Class"); } catch(ArithmeticException e) { System.out.println("ArithmeticException Class"); } } }The compiler outputs that ArithmeticException has been caught, which means that the above Exception has caught this exception and there is no need to catch it again.
What would happen if these two catches were reversed?
public class CatchDemo { //Division operation public static int division(int a,int b) { return a / b; } public static void main(String[] args) { try { CatchDemo.division(4,0); } catch (ArithmeticException e) { System.out.println("ArithmeticException Class"); } catch(Exception e) { System.out.println("Exception Class"); } } }At this time we found that the code passed the compilation, and the execution result was that ArithmeticException caught this exception, but the subsequent catch did not catch it.
I hope this article will be helpful to everyone’s Java programming.