异常
异常的概念:
什么是异常:
程序生病了??非正常可以执行完毕|编译期就检测出问题
异常一旦出现:1)程序无法执行
2)终止程序的继续执行,抛出异常的信息展示给程序员
异常的体系:
Throwable : 类是Java语言中所有错误和异常的超类。
**/ \ **
Error Exception
Error : 一般是由虚拟机生成并脱出的,不由程序员🐒控制
Exception : 异常
CheckedException检查时异常|编译时异常 : 发生在程序需编译期间,如果程序员不处理程序无法运行 ---->通过异常的处理方案(2种)
RuntimeException运行时异常 : 发生在程序运行期间,不处理程序终止执行 --->通过异常的处理方案(2种) | 增强程序健壮性if (推荐)
简答题:请说出常见的5种运行时异常?
异常的处理方案*******
==异常抛出:throws== 可以实现抛出多个异常,跑到上一层,由调用者解决处理;
==异常捕获:==
==try=={
有可能出现异常的代码段; }
**==catch==**(异常类型 引用){
捕获了对应类型异常后执行的代码;
}.....
**==finally==**{
无论是否出现异常都会执行的代码段...
一般定义资源的关闭等代码;
}
如果try中的代码从上到下执行没有遇到异常,catch不会执行;
如果try中代码一旦遇到异常,try后面的代码不再执行,从上到下执行catch判断哪一个catch所捕获的异常类型满足,执行对应的catch后的语句体;
一个try后面可以接1~n个catch;
接收异常类型较大的catch放在后面;
代码块:
public class Class002_Exception {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("main开始");
try{
System.out.println("try开始");
test();
//System.out.println(5/0);
System.out.println("try结束");
}catch(FileNotFoundException e){
System.out.println("遇到文件未找到异常了....");
}catch(ArithmeticException e){
System.out.println("数学异常");
}catch(Exception e){
//e.printStackTrace();
System.out.println(e.getMessage());
}finally {
System.out.println("最后的最后我们都会离开....");
}
System.out.println("main结束");
}
public static void test() throws FileNotFoundException {
InputStream is = new FileInputStream("D://test.txt");
}
}
自定义异常(了解)
异常也是类,需要继承自异常体系
如果直接或者间接的继承自RuntimeException,当前异常类为运行时异常
如果直接继承自Exception,或者没有继承RuntimeException,继承了Exception其他子类,这样异常为一个编译时异常
throw制造异常
代码块:
public class Class003_Defined {
public static void main(String[] args) {
User user = new User();
user.setUsername("zhangsan");
user.setPassword("1234");
int age = -19;
/*if(age>=18){
user.setAge(age);
}else{
user.setAge(18);
}*/
try {
user.setAge(age);
} catch (AgeException e) {
try {
user.setAge(18);
} catch (AgeException ageException) {
ageException.printStackTrace();
}
}
user.show();
}
}
//年龄不合法异常
//class AgeException extends RuntimeException{
class AgeException extends Exception{
public AgeException() {
}
public AgeException(String message) {
super(message);
}
}
//用户类型
class User{
private String username;
private String password;
private int age;
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if(age<18){
//制造一个异常
throw new AgeException(age+"不合法!!!");
}
this.age = age;
}
public void show(){
System.out.println(username+"-->"+password+"-->"+age);
}
}
代码块:
public class Class001_Exception {
public static void main(String[] args) {
//编译时异常
//InputStream is = new FileInputStream("D://test.txt");
String str = null;
if(str!=null){
System.out.println(str.length());
}
System.out.println("-----------------");
}
}