[Big Data] Study Notes 1 Java SE Chapter 8 Exception 8.2 Exception Handling

[Big Data] Study Notes

insert image description here

1 Java SE

Chapter 8 Exceptions

8.2 Exception handling

Five keywords for Java exception handling: try, catch, finally, throw, throws

8.2.1 Catch exception try...catch

[1] try...catch basic format

The catch exception syntax is as follows:

try{
    
    
     可能发生xx异常的代码
}catch(异常类型1  e){
    
    
     处理异常的代码1
}catch(异常类型2  e){
    
    
     处理异常的代码2
}
....

Write business logic code that may cause xx exceptions in try{}.

The catch branch is divided into two parts, the exception type and exception parameter name are written in catch(), and the code of what to do if this exception occurs is written in {}. If there are multiple catch branches, and multiple exception types have a parent-child relationship, it must be ensured that the small child exception type is at the top and the large parent exception type is at the bottom.

When an exception may occur in a certain piece of code, whether the exception is a compile-time exception (checked exception) or a runtime exception (unchecked exception), we can use a try block to enclose it and write a catch branch under the try block Try to catch the corresponding exception object.

  • If no exception occurs in the code in the try block when the program is running, then all branches of the catch will not be executed.
  • If an exception occurs in the code in the try block when the program is running, according to the type of the exception object, the first matching catch branch will be selected from top to bottom for execution. At this time, the code below the statement where the exception occurs in the try will not be executed, and the code after the entire try...catch can continue to run.
  • If an exception occurs in the code in the try block when the program is running, but none of the catch branches can match (catch) the exception, then the JVM will terminate the execution of the current method and "throw" the exception object to the caller. If the caller doesn't handle it, the program hangs.

Sample code:

package com.dingjiaxiong.keyword;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestTryCatch
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 14:58
 */

public class TestTryCatch {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            int a = Integer.parseInt(args[0]);
            int b = Integer.parseInt(args[1]);
            int result = a / b;
            System.out.println("result = " + result);
        } catch (NumberFormatException e) {
    
    
            System.out.println("数字格式不正确,请输入两个整数");
        } catch (ArrayIndexOutOfBoundsException e) {
    
    
            System.out.println("数字个数不正确,请输入两个整数");
        } catch (ArithmeticException e) {
    
    
            System.out.println("第二个整数不能为0");
        }

        System.out.println("你输入了" + args.length + "个参数。");
        System.out.println("你输入的被除数和除数分别是:");
        for (int i = 0; i < args.length; i++) {
    
    
            System.out.print(args[i] + "  ");
        }
        System.out.println();
    }
}

operation result

insert image description here

insert image description here

【2】JDK1.7 try...catch new features

If the exception handling codes of multiple catch branches are consistent, the following writing is also supported after JDK1.7:

try{
    
    
     可能发生xx异常的代码
}catch(异常类型1 | 异常类型2  e){
    
    
     处理异常的代码1
}catch(异常类型3  e){
    
    
     处理异常的代码2
}
....

Sample code:

package com.dingjiaxiong.keyword;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestJDK7
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:06
 */

public class TestJDK7 {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            int a = Integer.parseInt(args[0]);
            int b = Integer.parseInt(args[1]);
            int result = a / b;
            System.out.println("result = " + result);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
    
    
            System.out.println("数字格式不正确,请输入两个整数");
        } catch (ArithmeticException e) {
    
    
            System.out.println("第二个整数不能为0");
        }

        System.out.println("你输入了" + args.length + "个参数。");
        System.out.println("你输入的被除数和除数分别是:");
        for (int i = 0; i < args.length; i++) {
    
    
            System.out.print(args[i] + "  ");
        }
        System.out.println();
    }
}

insert image description here

[3] Obtain exception information in the catch branch

How to obtain exception information, some viewing methods are defined in the Throwable class:

  • public String getMessage(): Obtain the description information of the exception, the reason (when prompted to the user, it will prompt the cause of the error.

  • public void printStackTrace(): Print the exception trace stack information and output to the console.

​ Contains the type of exception, the cause of the exception, and the location where the exception occurred. In the development and debugging stages, printStackTrace must be used.

8.2.2 finally block

【1】finally block

Because the exception will cause the program to jump, which will cause some statements to not be executed. And there are some specific codes in the program that need to be executed regardless of whether an exception occurs. For example, the closing of the IO stream, the disconnection of the database connection, etc. Such code is usually placed in a finally block.

 try{
    
    
     
 }catch(...){
    
    
     
 }finally{
    
    
     无论try中是否发生异常,也无论catch是否捕获异常,也不管trycatch中是否有return语句,都一定会执行
 }
 
  try{
    
    
     
 }finally{
    
    
     无论try中是否发生异常,也不管try中是否有return语句,都一定会执行。
 } 

Note: finally cannot be used alone.

When the relevant methods of exiting the JVM are only called in try or catch, such as System.exit(0), finally will not be executed at this time, otherwise finally will always be executed.

Sample code:

package com.dingjiaxiong.keyword;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestFinally
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:08
 */

public class TestFinally {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        try {
    
    
            System.out.print("请输入第一个整数:");
            int a = input.nextInt();
            System.out.print("请输入第二个整数:");
            int b = input.nextInt();
            int result = a / b;
            System.out.println(a + "/" + b + "=" + result);
        } catch (InputMismatchException e) {
    
    
            System.out.println("数字格式不正确,请输入两个整数");
        } catch (ArithmeticException e) {
    
    
            System.out.println("第二个整数不能为0");
        } finally {
    
    
            System.out.println("程序结束,释放资源");
            input.close();
        }
    }
}

insert image description here

【2】finally and return

Form 1: return from try

package com.dingjiaxiong.keyword;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestReturn
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:09
 */

public class TestReturn {
    
    
    public static void main(String[] args) {
    
    
        int result = test("12");
        System.out.println(result);
    }

    public static int test(String str) {
    
    
        try {
    
    
            Integer.parseInt(str);
            return 1;
        } catch (NumberFormatException e) {
    
    
            return -1;
        } finally {
    
    
            System.out.println("test结束");
        }
    }
}

insert image description here

Form 2: return from catch

package com.dingjiaxiong.keyword;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestReturn
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:09
 */

public class TestReturn {
    
    
    public static void main(String[] args) {
    
    
        int result = test("a");
        System.out.println(result);
    }

    public static int test(String str) {
    
    
        try {
    
    
            Integer.parseInt(str);
            return 1;
        } catch (NumberFormatException e) {
    
    
            return -1;
        } finally {
    
    
            System.out.println("test结束");
        }
    }
}

insert image description here

Form 3: Return from finally

package com.dingjiaxiong.keyword;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestReturn
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:09
 */

public class TestReturn {
    
    
    public static void main(String[] args) {
    
    
        int result = test("a");
        System.out.println(result);
    }

    public static int test(String str) {
    
    
        try {
    
    
            Integer.parseInt(str);
            return 1;
        } catch (NumberFormatException e) {
    
    
            return -1;
        } finally {
    
    
            System.out.println("test结束");
            return 0;
        }
    }
}

insert image description here

8.2.3 Convert exception handling location throws

[1] throws compile-time exception

If when writing the code of the method body, a certain line of code may occurcompile time exception, Compilation fails without processing, but it may not be suitable for processing in the current method body or cannot give a reasonable processing method, you can declare in the method signature that the method may have xx exceptions through throws, which needs to be handled by the caller.

Declaration exception format:

修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{   }	

Multiple exception types can be written after throws, separated by commas.

Code demo:

package com.dingjiaxiong.keyword;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestThrowsCheckedException
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:12
 */

public class TestThrowsCheckedException {
    
    
    public static void main(String[] args) {
    
    
        System.out.println("上课.....");
        try {
    
    
            afterClass();//换到这里处理异常
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
            System.out.println("准备提前上课");
        }
        System.out.println("上课.....");
    }

    public static void afterClass() throws InterruptedException {
    
    
        for (int i = 10; i >= 1; i--) {
    
    
            Thread.sleep(1000);//本来应该在这里处理异常
            System.out.println("距离上课还有:" + i + "分钟");
        }
    }
}

insert image description here

【2】throws runtime exception

Of course, the runtime exception type can also be written after throws, but the runtime exception type, writing or not writing makes no difference to the compiler and program execution. If it is written, the only difference is that after the caller calls the method, when using the try...catch structure, IDEA can get more information and what catch branch needs to be added.

package com.dingjiaxiong.keyword;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestThrowsRuntimeException
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:13
 */

public class TestThrowsRuntimeException {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        try {
    
    
            System.out.print("请输入第一个整数:");
            int a = input.nextInt();
            System.out.print("请输入第二个整数:");
            int b = input.nextInt();
            int result = divide(a, b);
            System.out.println(a + "/" + b + "=" + result);
        } catch (ArithmeticException | InputMismatchException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            input.close();
        }
    }

    public static int divide(int a, int b) throws ArithmeticException {
    
    
        return a / b;
    }
}

insert image description here

[3] Method rewriting requires throws

When a method is rewritten, there are strict requirements for the method signature:

(1) The method names must be the same

(2) The formal parameter list must be the same

(3) Return value type

  • Basic data type and void: must be the same
  • Reference data type: <=

(4) Permission modifier: >=, and requires the overridden method of the parent class to be visible in the subclass

(5) Cannot be static, final modified method

(6) Throws exception list requirements

  • If there is no "throws compile-time exception type" after the method signature of the overridden method of the parent class, then when the method is rewritten, "throws compile-time exception type" cannot appear after the method signature.
  • If the method signature of the overridden method of the parent class is followed by "throws compile-time exception type", then when the method is overridden, the compile-time exception type of throws must be <= the compile-time exception type of throws of the overridden method.
  • Method override, no requirement for "throws runtime exception type".
package com.dingjiaxiong.keyword;

import java.io.IOException;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestOverride
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:14
 */

public class TestOverride {
    
    

}

class Father {
    
    
    public void method() throws Exception {
    
    
        System.out.println("Father.method");
    }
}

class Son extends Father {
    
    
    @Override
    public void method() throws IOException, ClassCastException {
    
    
        System.out.println("Son.method");
    }
}
8.2.4 Abnormal throw

If an exception occurs during the execution of a Java program, an exception object will be generated, and the exception object will be submitted to the Java runtime system. This process is called throwing an exception. There are two ways to generate exception objects:

  • Automatically generated by the virtual machine: During the running of the program, if the virtual machine detects that there is a problem with the program, it will automatically create an instance object corresponding to the exception class in the background and throw it—automatically throw.
  • Manually created by the developer: new exception type ([actual parameter list]);, if the created exception object does not throw, it will have no impact on the program, just like creating a normal object, but once throw is thrown, it will have no impact on the program Operation has an impact.

Use the format:

throw new 异常类名(参数);

The exception object thrown by the throw statement is the same as the exception object automatically created and thrown by the JVM.

  • If it is an object of an exception type at compile time, it also needs to use throws or try...catch to handle it, otherwise the compilation will fail.
  • If it is an object of runtime exception type, the compiler does not prompt.
  • However, whether it is an object of an exception type at compile time or an object of an exception type at runtime, if it is not properly handled by try...catch, it will cause the program to crash.

The throw statement will cause the program execution flow to be changed. The throw statement explicitly throws an exception object, so the code below it will not be executed. If the current method does not have a try...catch to handle the exception object, the throw statement will replace the return statement in advance Terminates the execution of the current method and returns an exception object to the caller.

package com.dingjiaxiong.keyword;

/**
 * @Projectname: BigDataStudy
 * @Classname: TestThrow
 * @Author: Ding Jiaxiong
 * @Date:2023/4/27 15:15
 */

public class TestThrow {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            System.out.println(max());
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        try {
    
    
            System.out.println(max(4));
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        try {
    
    
            System.out.println(max(4, 2, 31, 1));
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }

    public static int max(int... nums) {
    
    
        if (nums == null || nums.length == 0) {
    
    
            throw new IllegalArgumentException("没有传入任何整数,无法获取最大值");
        }
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
    
    
            if (nums[i] > max) {
    
    
                max = nums[i];
            }
        }
        return max;
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44226181/article/details/130480074
Recommended