Java reading note One (exception handling)

Source: Internet
Author: User
Tags finally block getmessage

1. Introduction

In the development process, will encounter the program runtime exceptions, such as logic errors, hardware failures, and so on, this blog will be a detailed introduction of Java in the exception handling mechanism.


2.Try and catch catch exceptions

The try and catch statements are often used in the process of handling exceptions. A try statement block can indicate an exception that can occur and is then captured by one or more catch statement blocks.

2.1. Simple try and catch syntax

Package com. Runtimeexception;public class Sample11_1{public static void Main (string[] args) {//Monitored code block try{//create array object int[] a=new int[4 ]; System.out.println ("Integer array creation complete!! ");//access array element a[3]=9; System.out.println ("The value of the fourth element in the integer array is" +a[3]+ "!!!");} Handle subscript out of bounds exception catch (ArrayIndexOutOfBoundsException Aiobe) {//print hint Info System.out.println ("The type of error that appears here is: array subscript out of bounds!! ");} Handling null Reference exception catch (NullPointerException NPE) {//Print hint information System.out.println ("The type of error that appears here is: null reference!! ");} SYSTEM.OUT.PRINTLN ("The main program is finished!!! ");}}

2.2. Abnormal propagation process

During the propagation of an exception, if no catch statement is caught, the exception is propagated upward along the call stack of the method. If a catch statement block is not captured during propagation, it is eventually propagated to the main method and finally thrown by the main method, which is handled by the Java Runtime environment.

Package com. Runtimeexception;import Java.io.ioexception;import Java.net.serversocket;public class Sample11_2 {public static void Main (string[] args) {//Method1 method called in Main method Method1 ();} The static void Method1 () {///Method1 method calls the Method2 method Method2 ();} static void Method2 () {int[] a = new int[3];//produces data subscript out of bounds error a[4] = 12; SYSTEM.OUT.PRINTLN ("OK!!!");}}

2. The role of 3.finally statement blocks

In some special cases, when a program fails, it must be guaranteed to execute, regardless of whether the exception is thrown or not. For example, a database connection is opened, regardless of whether an exception is thrown during processing, the connection is closed, and the execution cannot be affected by throwing an exception. You can then place the statement that must be executed in the finally.

Package com. Runtimeexception;public class Sample11_3 {public static void main (string[] args) {//Monitored code block try{//create an array of type int of length 4 int[] A= New Int[4]; System.out.println ("Integer array creation complete!! ");//The last element of the array is assigned a value of a[3]=9; System.out.println ("The value of the fourth element in the integer array is" +a[5]);} Handling null reference exception code block catch (NullPointerException NPE) {//print hint Info System.out.println ("The type of error that appears here is: null reference!! ");} Finally block finally{//print hint information System.out.println ("Here is the finally block, regardless of whether or not to throw an exception, this is always done!") ");}}}

issues needing attention between 2.4.try, catch, and finally

~ If there is no catch, finally must follow the try

~catch and finally cannot be omitted at the same time

No additional code can be inserted between ~try, catch, and finally blocks


3. The hierarchy of exceptions

When an exception occurs, Java wraps the exception as an object of the exception class and passes its reference action parameter to the corresponding catch statement for processing. Exceptions are caught in Java in two-part catch and uncaught exceptions


3.1. Exception level diagram


~ The Throwable class has two direct subclasses, the error and the exception class, and the exception class has a subclass runtimeexception.

~ Catch exceptions are generally generated by external factors, and can be recovered, not by the program, the exception program itself is not a problem can also be produced.

~ uncaught exception, which is the error class and its subclasses, and the RuntimeException class and its subclasses

~ The types of exceptions that are caught require capture processing in the program.


3.2. Abnormal explicit re-throw

For caught exceptions, when the method declaration is thrown, it can be thrown again through a try and catch.

Package com. Runtimeexception;import Java.io.ioexception;import Java.net.serversocket;public class Sample11_10 {// Defining the Connect method will likely throw IOException exception public void Connect () throws IOException {//monitored code try {//Create ServerSocket Object ServerSocket SS = new ServerSocket (9999);} Exception handling code catch (IOException E) {//throws exception throw throw E;}}}

3.3. Stealth re-throw

If you just want to throw the exception again, you do not have to use the explicit re-throw, the direct use of stealth and then throw it.

Package com. Runtimeexception;import Java.io.ioexception;import Java.net.serversocket;public class Sample11_12 {// Declaring a method myFunction will likely throw IOException exception public static void MyFunction () throws ioexception{//Create ServerSocket object ServerSocket Ss=new ServerSocket (9999);} public static void Main (string[] args) {//Monitored code try{//calls MyFunction method MyFunction ();} Exception handling code catch (IOException E) {//Print call stack information e.printstacktrace ();} System.out.println ("Congratulations, the program is finished!!!" ");}}

4. Custom exception classes

We can also customize our own exception classes to meet our own needs.

4.1. Create a custom exception class

Generally, if you create a custom exception class, you simply inherit exception or other catch exception classes, which are commonly used in the following ways

~printstacktrace (): The method will print the information of the exception call stack on the console

~tostring (): The method returns the string representation of the exception object

~getmessage (): Returns the error message that is carried in the exception.

Package com. Runtimeexception;class MyException extends exception{//two versions of the builder public myexception () {}public myexception (String msg) { Super (MSG);}} Main class public class Sample11_15{public static void Main (string[] args) {//Create custom Exception class object MyException me=new myexception ("Custom Exception class Me.printstacktrace ();//Call the inherited method System.out.println ("The string representation of the custom exception object is:" "+me.tostring () +" ". "); System.out.println ("The custom exception object carries an error message:" "+me.getmessage () +" ".) ");}}

4.2. Simultaneous capture of multiple exceptions

If a try statement is followed by more than one catch, the order of the last catch statement satisfies the small-to-large range to capture, that is, the exception begins with the subclass and slowly increments.



Java reading note One (exception handling)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.