小结:
- 如果没有出现异常,则执行try块中所有语句,不执行catch中所有的语句,如果有finaily,最后还需要执行finally里面的语句。
- 如果出现异常,则try块中异常发生后,try块剩下的语句不再执行。将执行catch块中的语句,如果有finally,最后还需要执行finally里面的语句! ```java package test;
public class Main { public static int method() { try { String[] names = new String[3];//String[]数组 if (names[1].equals(“tom”)) {//NullPointerException System.out.println(names[1]); } else { names[3] = “WTY2002”; } return 1; } catch (ArrayIndexOutOfBoundsException e) { return 2; } catch (NullPointerException e) {//捕获 return 3; } finally { //必须执行 return 4; //返回4 } }
public static void main(String[] args) {
System.out.println(method()); //4
}
}
![image.png](https://cdn.nlark.com/yuque/0/2021/png/21705001/1639019462959-4d2744d1-0652-4e99-a15f-8a1887b3b913.png#clientId=u779ef558-72f4-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=166&id=u6bedc7e4&margin=%5Bobject%20Object%5D&name=image.png&originHeight=142&originWidth=645&originalType=binary&ratio=1&rotation=0&showTitle=false&size=44269&status=done&style=none&taskId=u0b68a01e-ff9f-4d3c-9a1f-fc08d807aae&title=&width=754)
```java
package test;
public class Main {
}
class Exception {
public static int method() {
int i = 1;
try {
i++; //i = 2
String[] names = new String[3];
if (names[1].equals("tom")) {//空指针
System.out.println(names[1]);
} else {
names[3] = "WTY2002";
}
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 2;
} catch (NullPointerException e) {
System.out.println("========");
return ++i; //i = 3
} finally {//必须执行
return ++i; //i = 4
}
}
public static void main(String[] args) {
System.out.println(method());
}
}
package test;
public class Main {
}
class ExceptionExe01 {
public static int method() {
int i = 1;//i = 1
try {
i++;// i=2
String[] names = new String[3];
if (names[1].equals("tom")) { //空指针
System.out.println(names[1]);
} else {
names[3] = "hspedu";
}
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 2;
} catch (NullPointerException e) {
return ++i; // i = 3 => 保存临时变量 temp = 3;
} finally {
++i; //i = 4
System.out.println("i=" + i);// i = 4
}
}
public static void main(String[] args) {
System.out.println(method());// 3
}
}
package test;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//如果用户输入的不是一个整数,就提示他反复输入,直到输入一个整数为止
//思路
//1. 创建Scanner对象
//2. 使用无限循环,去接收一个输入
//3. 然后将该输入的值,转成一个int
//4. 如果在转换时,抛出异常,说明输入的内容不是一个可以转成int的内容
//5. 如果没有抛出异常,则break 该循环
Scanner scanner = new Scanner(System.in);
int num = 0;
String inputStr = "";
while (true) {
System.out.println("请输入一个整数:"); //
inputStr = scanner.next();
try {
num = Integer.parseInt(inputStr); //这里是可能抛出异常
break;
} catch (NumberFormatException e) {
System.out.println("你输入的不是一个整数:");
}
}
System.out.println("你输入的值是 = " + num);
}
}