3.
Try-catchBlock
There are three scenarios in which code executes in a try statement block:
- The code in the try statement block executes properly without any exception, and the code for the catch statement block will not be executed.
import java.util.*;public class Count { public static void main (String []args){ int a , b; Scanner read = new Scanner(System.in); try{ System.out.print("请输入a:"); a = read.nextInt(); System.out.print("请输入b:"); b = read.nextInt(); System.out.println("a+b="+(a+b)); }catch(InputMismatchException ex){ System.out.println("不可以,请输数字!"); } System.out.println("<<<<欢迎使用!>>>>"); }}
Enter 100 and 200 after the program goes smoothly!
- An exception is generated during code execution in a try statement block, and the exception is consistent with the type of exception declared in the catch , then the remaining code in the try statement block is ignored, and thecatch The code for the statement block is executed.
Or the above code, enter 100 and a after the program runs as follows:
- An exception is generated during code execution in a try statement block, but the exception thrown is not declared in the catch statement block, and the program terminates immediately.
4.
try-catch-finallyBlock
Adding a finally block after the catch clause ensures that the code in thefinally block is always executed, regardless of whether an exception occurs.
import java.util.*;public class Count { public static void main (String []args){ int a , b; Scanner read = new Scanner(System.in); try{ System.out.print("请输入a:"); a = read.nextInt(); System.out.print("请输入b:"); b = read.nextInt(); System.out.println("a+b="+(a+b)); }catch(Exception ex){ System.out.println("不可以,请输数字!"); }finally{ System.out.println("<<<<欢迎使用!>>>>"); } }}
5. Multiple
CatchBlock
- A piece of code can produce multiple exceptions.
- The exception object declared by each catch block is checked in turn to find a catch block that performs the first match of the exception type thrown by the try , and then the catch block is ignored.
- The exception subclass must precede the exception parent class, such as:
--------------------------------------------------------------------------------------------------------------- ----------------------------------
What do I (Java) do with a sudden "break exception"?