Exception Handling in Java

Exceptions are not normal by name. Java provides us with exception classes for us to deal with exceptions that may occur at compile time and runtime.

The root class of the exception class in Java is Throwable, and it has two subclasses: Error and Exciption. Error refers to errors, which are generally problems generated by JVM and do not need to be solved by ourselves. Exciption is what we call exceptions, which are generally divided into There are two types: one is a runtime exception (RuntimeExciption), and the other is a non-runtime exception. According to whether it is checked, it can be divided into checked exceptions and unchecked exceptions.

Use of runtime exceptions:
 * There are two mechanisms for exception handling in Java:
 * 1. try-catch-finally
 * try: try. The code that may generate an exception needs to try to run
 * catch: catch. Generated exception
 * finally: Final execution.
 * Whether try generates an exception or catch catches an exception. Finally will be executed.

 * 2.throw 和 throws

Let's look at the sample code:

    The package to be imported: import java.util.InputMismatchException;

public class ExceptionDemo01 {

    public static void main(String [] args){

        //-- When making input, the user will be restricted to only input numbers. If the input character is prompted, the input is wrong
        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter a number:");
        int num = 0;
        A:for (;true;){
            try{
                num = scan.nextInt();
                break;
                //-- e represents the caught exception object. The name can be written arbitrarily. But the general habit is to use e
            }catch (InputMismatchException e){
                System.out.println("Incorrect input, please re-enter");
                //-- Gets the wrong value retained in the buffer.
                scan.next();
//                continue A;
                e.printStackTrace ();
            }
        }
        System.out.println("num:" + num);

    }

}

Look at another example:

NumberFormatException
 *
 * When an application attempts to convert a string to a numeric type,
 * This exception is thrown when the string cannot be converted into an appropriate format.
 *
 * 1. The condition for this exception: It may be triggered when converting a string to a value
 * There are non-numeric parts in the string. Or just an empty string. Put this
 * String is converted to a value. This exception will be generated.
 *
 * 2. How to run the code without ending the code when it is encountered, without seeing the exception information.
 * @author Administrator
 */
public class ExceptionDemo02 {

    public static void main(String [] args){

        String str = "a";
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter:");
        str = scan.next();
        //str = "";
        int num = 0;
        for ( ; true ;){
            try{
                //-- turn numbers into strings
                //String.valueOf();
                //-- turn the string into a number
                num = Integer.parseInt(str);
                break;
            }catch (NumberFormatException e){
                /**
                 * If the exception does not generate Catch will not execute.
                 */
                System.out.println("Conversion failed, re-enter");
                //-- next here is to re-enter, not to clean up.
                str = scan.next();
            }
        }
        System.out.println(num);
    }
}

example:

public class ExceptionDemo03 {

    public static void main(String [] args){

        /*
            Null Pointer Exception: NullPointerException
            It's because the reference variable doesn't point to the actual object (except for null). But by the reference variable
            When a property or method of an object is manipulated, a null pointer will be generated. Once a null pointer is generated, it must be
            Empty before the dot. Reference variable. Property reference variable. Method()
            X.Y.Z.
            The default value of a reference data type is null
         */
        String str = "";
        try {
            System.out.println(1);
            //-- A null pointer is generated below, and it goes directly into the catch. The output statement 2 will not be executed.
            //-- When an exception is generated in try, the code below the exception will not be executed.
            System.out.println(str.length());
            System.out.println(2);
        }catch (NullPointerException e){
            System.out.println(3);
        }finally {
            //- Regardless of whether an exception is generated in try, whether or not catch catches an exception. finally will be executed.
            System.out.println(4);
        }

    }
}

public class ExceptionDemo04 {

    public static void main(String [] args){

        /*
            Null Pointer Exception: NullPointerException
            It's because the reference variable doesn't point to the actual object (except for null). But by the reference variable
            When a property or method of an object is manipulated, a null pointer will be generated. Once a null pointer is generated, it must be
            Empty before the dot. Reference variable. Property reference variable. Method()
            X.Y.Z.
            The default value of a reference data type is null
         */
        String str = null;
        try {
           //-- Problem? Is it possible to generate a different exception in try.
            System.out.println(1);
            //System.out.println(str.length());
            //System.out.println(Integer.parseInt(str));
            System.out.println(Integer.parseInt(str.length()+""));
            System.out.println(2);
        }catch (NullPointerException e){
            System.out.println(3);
        }catch (NumberFormatException e){
            System.out.println(4);
        }catch (InputMismatchException e){
 
 
public class ExceptionDemo06 {

    public static void main(String [] args){
        ExceptionDemo06 ed = new ExceptionDemo06();
        System.out.println(ed.method(null));
    }

    public int method(String str){
        try{
            System.out.println("A");
            System.out.println(str.length());
            return 1;
        }catch (NullPointerException e){
            System.out.println("B");
            return 2;
        }catch (Exception e){
            System.out.println("C");
            return 3;
        }finally {
            //-- The return in catch is executed, but the method does not end. Instead, the result of return is selectively saved
            //-- in a temporary cache
            System.out.println("D");
            //-- The return at this time overwrites the result of the return above.
            return 4;
        }
    }
}    
public class ExceptionDemo07 {

    public static void main(String [] args){
        ExceptionDemo07 ed = new ExceptionDemo07();
        ed.method2(null);
    }

    public void method(String str) {
        try {
            System.out.println(str.length());
        } catch (NullPointerException e) {
            System.out.println("Parameter is empty");
        } finally {
            //The code in finally may also generate exceptions
            try{
                System.out.println("Get from new");
                str = null;
            }catch (Exception e) {

            }finally{//-- this finally can choose not to add

            }
        }
    }

    /**
     * Rewrite the following style when some try-catch is needed in finally.
     * @param str
     */
    public void method2(String str){
        try{
            System.out.println(1);
            try{
                System.out.println(2);
                System.out.println(str.length());
                System.out.println(3);
            }finally {
                System.out.println(4);
            }
        }catch (NullPointerException e){
            System.out.println(5);
        }
    }
}

Next look at throw and throws :

 * Checked and unchecked, checked by the compiler.
 * Exceptions that can be checked by the compiler during code writing are called checked exceptions.
 * All exceptions except RuntimeException and its subclasses are checked
 *
 * non-runtime exception == checked exception
 * runtime exception == non-spot- checked exception
 *
 * throw and throws are negative exception handling methods.
 * throws is used in method declarations. Indicates that the method may generate one or more exceptions .And the current method
 * does not handle the exception, and hands it to the JVM for processing. The JVM forces it to be handled by the caller.
 *
 * throw defines an exception object at the current location. (There is an actual exception generated)

Let's look at the sample code:

public class ThrowDemo01 {

    public static void main(String [] args){
       ThrowDemo01 td = new ThrowDemo01();
       td.method(null);
    }

    /**
     *
     */
    public boolean method(){
        //throw + exception object
        /*
        In a method with a return value, I hope the current method ends, but I don't want to give the return value
        In this case, you can choose to throw an exception out.
         */
        throw new NullPointerException("Wrong password");
        //-- When the code executes to the above line, the method has ended, and the following statement will not be executed. So
        //-- It's useless to write it.
    }


    /**
     * throw + catch combined writing
     * @param str
     */
    public void method(String str){
        try{
            System.out.println(str.length());
        }catch (NullPointerException e){
            throw e;
        }
    }
}

throws:

public class ThrowsDemo01 {

    public static void main(String [] args){

        ThrowsDemo01 td = new ThrowsDemo01();
        td.method();
    }

    /**
     * throws can only be used in method declarations.
     * @throws NullPointerException
     */
    public void method() throws NullPointerException{
        String str = null;
        /*
        If it is a runtime exception (unchecked exception), the exception is handed over to the JVM for processing
        If it is a non-runtime exception (checked exception), the place where the method is called must use a try-catch to handle the exception.
         */
        System.out.println(str.length());
    }
}

Let's look at another example: custom exception:

     In the user login system, the login user name and password need to be verified. Let's look at the code directly:

First define three classes to inherit the Exciption class:

Custom y exception: The passed parameter is abnormal.
 * Custom exception process:
 * 1. Provide a class to inherit the existing exception class. (Exception or other subclasses)
 * 2. Provide parameterized and parameterless construction methods
 * The parameter type is basically String.
 * 3. Override the getMessage method.
 *
 *
 * Directly inheriting Exception is to spot check exceptions, not runtime exceptions.
 * @author Administrator
 */
public class ArgumentException extends Exception{
    public ArgumentException(){

    }
    public ArgumentException(String msg){
        super(msg);
    }

    /**
     * Return what you want the user to see.
     * @return
     */
    @Override
    public String getMessage() {
        return "parameter exception";
    }
}

Password exception class:

public class PwdErrorException extends Exception{
    public PwdErrorException(){

    }
    public PwdErrorException(String msg){
        super(msg);
    }

    /**
     * Return what you want the user to see.
     * @return
     */
    @Override
    public String getMessage() {
        return "Incorrect password";
    }
}

Username exception class:

public class UnKnownNameException extends Exception{
    public UnKnownNameException(){

    }
    public UnKnownNameException(String msg){
        super(msg);
    }

    /**
     * Return what you want the user to see.
     * @return
     */
    @Override
    public String getMessage() {
        return "Username does not exist";
    }
}

User business class:

public class UserBizImpl {

    public void userLogin(String name,String pwd) throws ArgumentException,UnKnownNameException,PwdErrorException{

        if (name == null || pwd == null || name.length() == 0 || pwd.length() == 0){
            //- Because the throw here is a non-runtime. So it must be written in conjunction with throws
            throw new ArgumentException();
        }

        if ("admin".equalsIgnoreCase(name) && "123".equalsIgnoreCase(pwd)){
            System.out.println("Login successful");
        }else if(!"admin".equalsIgnoreCase(name) && "123".equalsIgnoreCase(pwd)){
            throw new UnKnownNameException();
        }else{
            throw new PwdErrorException();
        }
    }

}

Test class:

public class Test {
    public static void main(String [] args){

        UserBizImpl userBiz = new UserBizImpl();
        try {
            userBiz.userLogin("admin","123");
        } catch (ArgumentException e) {
            System.out.println(e.getMessage());
        } catch (UnKnownNameException e) {
            System.out.println(e.getMessage());
            //e.printStackTrace();
        } catch (PwdErrorException e) {
            System.out.println(e.getMessage());
        }catch (Exception e){
            System.out.println("Prevent missing exceptions!");
        }
    }
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324734468&siteId=291194637