新知识点:
1.共有5个关键字 4个已学 try catch throw throws
问题:
1.如果不抛异常,则顺序执行,但越过catch语句块,然后往下执行catch之后的语句块
2.如果try中的代码抛出了异常,那么try中余下的代码还执不执行? -------不执行
2 跳转到相应的catch语句块中,执行catch里面的代码
如果catch语句块使用了throw,那么throw后的语句(无论是在catch语句之中还是catch语句之后)不再执行
确保代码一定能够执行 finally
try {
} catch () {
} finally {
}
3.一张图:(组织关系图): 很多异常类----OOP 继承 父类 Object
类: Throwable 有两个分支 Error Exception (系统环境错误) (程序员违背了某种规则) ..... RuntimeException ..... ArithmeticException ArrayIndexOutofBoundsException NullPointerException
|
try : 可能发生异常的代码要封装在try语句块中 会增加代码量。设计师把一些经常发生的异常进行“处理”,这些代码可以不用放在try 中。RuntimeException 中的异常可以不用写在try语句中
public class B {
public static void main(String[] args) {
}
public static void m1(int a) {
int result = 0;
int[] arr = {1,2,3};
String str = null;
//String str = new String();
result = 10/0; //ArithmeticException
System.out.println(arr[4]); //ArrayIndexOurofBoundsException
Str.split(","); //NullPointerException
}
}
4.先捉小的,后捉大的
如果try 语句块抛出多种异常,那么:
4.1 规范格式:用catch 分别捕捉-----catch语句块的顺序
是不是抛出异常的顺序?
---不是~!因为try抛出异常,JVM 会跳转到相应的catch 执行
catch捕捉到的多个异常类,如果存在“继承”关系,必须考虑“父类-子类”的顺序问题:
父类异常:位于子类异常的后面:------没有问题
父类异常:位于子类异常的前面:------不行!因为后面的子类异常永远都没有机会执行
try {
result = 10/0;
System.out.println(arr[5]);
Str.split(",");
}catch (NullPointerException e) {
} catch (ArrayIndexOutofBoundsException e) {
} catch (ArithmeticException e) {
} catch (RuntimeException e) { //父类
}
5. 自定义异常
模拟登陆 输入用户名zs, 提示正确,否则提示错误。
自定义异常 封装用户名不正确信息
语法:
继承自Exception(必须写 try catch)/ RuntimeException(可以不写 try catch )
================继承自Exception=======================
class UsernameNotFoundException extends Exception {
// className nethodName linenumber (前三者都不能确定)info
public UsernameNotFoundException(String info ) {
super(info);
//super("用户名不存在");
}
}
public class B {
public static void main(String[] args) {
try {
login();
} catch (Exception e) {
System.out.println("用户名不正确");
}
}
//登陆
public static String login() throws Exception{
String name = getName();
if ("zs".equals(name) {
System.out.println("登陆成功");
} else { //登陆不成功,认为是运行期错误---异常 -JDK 没有内置“用户名错误”的异常---已定义异常
Exception e = new UsernameNotFoundException();
throw e;
}
//键盘输入用户名
public static String getName() throws Exception {
return new BufferedRead(new InputStreamReader(System.in)).readLine();
}
}
=====================继承自RuntimeException=============================
class PasswardErrorException extends RuntimeException {
public PasswardErrorException(String info) {
super(info);
}
}
public class Test {
public static void main(String[] args) {
checkPwd(); //受控异常 不用写try catch
/*
try {
checkPwd();
} catch (PassWardErrorException) {
System.out.println("密码错误");
}
*/
}
public static void checkPwd() {
if ("123".equals(pwd)) {
System.out.println("跳转到成功页面");
} else {
throw new PassWardErrorException("密码错误");
}
}
public static String getPwd() {
String str = null;
try {
str = new BufferedRead(new InputStreamReader(System.in)).readLine();
} catch (IOException e) {
}
}
}