JAVA进阶知识点总结 5-异常 线程

01.第一章:异常_概念:

1).什么是“异常”:指程序在运行过程中遇到了一些无法处理的情况,这时JVM会向控制台打印错误信息,并停止程序。
这不是我们想看到的结果。基于此,Java为我们提供了一种“异常处理机制”可以使我们程序在发生异常情况时,
可以跳过异常的代码,继续向下执行。

2).JVM处理异常的默认方式:

1).JVM执行到有异常的代码;
2).JVM会识别出这种异常;

3).JVM会到类库中找到描述这种异常的“异常类”–JVM为每种异常情况都定义了“异常类”。并创建异常对象;

4).JVM会到代码中查看我们的代码是否“捕获”这种异常:

否:JVM向控制台打印异常信息,并结束程序;【之前的情况】
是:JVM会执行“异常处理代码-catch”–【今天讲的】

02.第一章:异常_异常和错误的区别

Throwable(所有异常的根类)
|–Error(错误):我们不需要捕获,因为捕获也没有意义;
|–Exception(异常):我们程序需要捕获并处理的。
|–RuntimeException(运行时异常):
|–其它的异常(编译期异常):

03.第一章:异常_常见的运行时异常:

1).空指针异常–NullPointerException:
int[] arr1 = null;
System.out.println(arr1.length);//NullPointerExcepiton–空指针异常

2).数组索引越界异常–ArrayIndexOutOfBoundsException:
int[] arr2 = {1,2,3};
System.out.println(arr2[30]);//ArrayIndexOutOfBoundsException–数组索引越界异常

3).字符串索引越界异常–StringIndexOutOfBoundsException
String str = “Hello”;
System.out.println(str.charAt(30));//StringIndexOutOfBoundsException–字符串索引越界

4).数学运算异常–ArithmaticException
int a = 10 / 0;
System.out.println("a = " + a);//ArithmeticException–数学运算异常

04.第一章:异常_异常处理_throw(抛出):【了解】

示例代码:

public class Demo {
    public static void main(String[] args) {
        int[] arr = null;
        if(arr == null){
            //抛出异常--抛给此方法的调用者--JVM
            throw new NullPointerException("空指针异常!");
        }
        System.out.println(arr.length);
    }
}

05.第一章:异常_异常处理_Objects_requireNonNull方法:【了解】

有时我们定义的类中的属性是不希望被赋值为:null的:

class Student{
		private String name;
		private String address;
		public Student(String name,String address){
			/*
			if(name == null){
				//抛出异常--相当于return,立即结束方法,向调用者返回一个异常对象
				throw new NullPointerException("名字不能为null");
			}
			if(address == null){
				throw new NullPointerException("地址不能为null");
			}
			*/
			//Objects的requeireNonNull()方法内部会判断参数是否为null,是:抛出异常
			//这样就不需要我们自己判断,它会为我们判断。
			this.name = Objects.requireNonNull(name);
			this.address = Objects.requireNonNull(address);
		}
	}
	main(){
		Student stu = new Student(null,"北京");
	}

05.第一章:异常_异常处理_throws(声明抛出):【掌握】

public static void main(String[] args) {
    int[] arr = {432,43,24,32,432,43,24,3243};
    int r = sum(null);
    System.out.println("累加和是" + r);


}

throws的作用:告诉JVM,我这个方法中可能会抛出这个异常,如果真的发生这个异常
请将这个异常对象抛给"调用处"。

public static int sum(int[] arr) throws NullPointerException,
                                        ArrayIndexOutOfBoundsException{
    int sum = 0;
    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];

    }
    return sum;
}

注意:
1.如果throws抛出的是“运行时异常”,调用处可以不处理,编译会通过,但如果真的出现异常,
仍然是终止程序。

2.如果throws抛出的是“编译期异常”,调用处必须处理(try…catch/抛出),否则编译错误。

06.第一章:异常_异常处理_try_catch语句:【掌握】

1).格式:

	try{
		//可能出现异常的代码
	}catch(异常类型名  变量名){
		//如果try中出现了与"异常类型名"一样的异常,就会执行这个
		//catch语句。
	}

2).示例代码:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    while(true) {
        System.out.println("请输入年龄:");
        try {
            int age = sc.nextInt();
            System.out.println("你的年龄是:" + age);
            break;
        } catch (InputMismatchException e) {
            sc = new Scanner(System.in);
            System.out.println("哥们,请输入数字!");
        }
    }
    System.out.println("后续程序...");
}

07.第一章:异常_异常处理_异常对象的操作:

public static void main(String[] args) {
    int[] arr = {1,2,3};
    try {
        System.out.println(arr[30]);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("异常信息:" + e.getMessage());//异常信息
        System.out.println("toString() : " + e.toString());//异常类名 + 异常信息
        e.printStackTrace();//常用,调试的时候。上线后-写日志

    }
}

08.第一章:异常_异常处理_多catch语句:

	try{
		//...
		//...
		//...
	}catch(异常类名1 变量名){
	}catch(异常类名2 变量名){
	}catch(异常类名3 变量名){
	}

示例代码:

public static void main(String[] args) {
    try {
        int[] arr = null;
        System.out.println(arr.length);//这里出异常--这里后面的代码将不会被执行

    int[] arr2 = {1, 2, 3};
    System.out.println(arr2[4]);

    int a = 10 / 0;
    System.out.println(a);
    //后续代码....

} catch (NullPointerException e) {
    System.out.println("空指针异常");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("数组索引越界异常!");
} catch (ArithmeticException e) {
    System.out.println("数学运算异常!");
} catch (Exception e) {
    System.out.println("其它的异常,由我来处理...");
    System.out.println("我只能写在多个catch的最后");
}
注意:如果异常类型有“父类”类型,要将父类的异常类型写在多catch的末尾
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
try {
    int[] arr = null;
    System.out.println(arr.length);//出异常,后面的try..catch语句还会被执行
} catch (NullPointerException e) {
    System.out.println("空指针异常!");
}
try {
    int[] arr2 = {1, 2, 3};
    System.out.println(arr2[4]);
} catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("空指针异常!");
    }
}

以后写方法时的建议:

public void show(){
				try{
				...
				try{
				}catch(...){
				}
				...
				...
				try{
				}catch(...){
				}
			}catch(Exception e){
			}
			}

09.第一章:异常_异常处理_try_catch_finally:
1).格式:

try{
	...
}catch(...){
	...
}finally{
	//无论是否出现都会被执行的代码
	//尤其在方法中,当try中有return时,需要关闭资源时尤其有用。
}

2).示例代码:

public class Demo {
    public static void main(String[] args) {
        file();
    }

    public static String file()   {
        try {
            System.out.println("打开文件...");
            System.out.println("读取文件...");
            int a = 10 / 0;
            return "文件内容";//在执行return的过程中,会去调用:finally
        }catch (Exception e){
            System.out.println("异常了...");
            return null;//在执行return的过程中,会去调用:finally
        }finally {
            System.out.println("关闭文件...");
        }
    }
}

10.第一章:异常_自定义的异常:

1).在我们的程序中,根据某些业务,需要抛出某种异常,但类库中没有,这时我们就可以自定义异常。例如:

class Student{
		private int age;
		public void setAge(int age){
			if(age < 15 || age > 50){
				//必须要想办法通知调用处,这个参数不正确。
				//抛出异常
				throw new 自定义异常对象();
			}
			this.age = age;
		}
	}

2).自定义异常:
1).自定义类继承自Exception(编译期异常)或者RuntimeException(运行时异常)

public class AgeException extends RuntimeException {
    public AgeException() {
    }

    public AgeException(String message) {
        super(message);
    }
}

2).使用自定义异常:

public class Student {
    private int age;

    public void setAge(int age) {
        if (age < 15 || age > 50) {
            throw new AgeException("哥们,年龄值必须在15到50之间!");
        }
        this.age = age;
    }
}

3).测试类:

public class Demo {
    public static void main(String[] args) {
        Student stu = new Student();
        try {
            stu.setAge(10);
        } catch (AgeException e) {
            System.out.println("异常信息:" + e.getMessage());
        }
    }
}

11.第一章:异常_子类重写父类方法时的异常抛出

	class Fu{
		public void show1()(//不抛出任何异常
		}
		public void show2() throws NullPointerException{//抛出运行时异常
		}
		public void show3() throws IOException{//编译期异常
		}
	}
	class Zi extends Fu{
		//子类重写三个方法,可以:
		1).不抛出任何异常
		2).可以抛出任何的“运行时异常”;
		3).不能抛出比父类更多的“编译器异常”
	}

12.第二章:多线程_常见概念:

1).什么是“进程”:“进程”是操作系统中的概念,指一个“独立运行的程序”。
2).什么是“线程”:“线程”由“进程”创建的,指一个进程,可以将一部分代码以“独立的方式”运行,
                  并且与“主进程”--“同时执行”,这样也就意味着,我们的程序可以同时做多件事情。
3).什么是“并行”:并行:指两个或多个事件在同一时刻发生(同时发生)
4).什么是“并发”:并发:指两个或多个事件在同一个时间段内发生。

13.第二章:多线程_实现线程的方式:

1).自定义类,继承自Thread,并且重写run()方法;
2).创建线程对象;
3).调用对象的start()方法:
示例代码:

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("鼓掌....");
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        //1.创建线程对象
        MyThread t = new MyThread();
        //2.启动线程
    //    t.run();//普通方法调用,不会启动线程
	 t.start();//启动线程
        //3.主线程会继续向下
        for (int i = 0; i < 100; i++) {
            System.out.println("吹口哨...");
        }
    }
}

4).注意事项:

1).重写的是run(),但启动线程调用的是start();
2).对于一个“线程对象”,只能start()一次,然后立即成为垃圾。
3).对于同一个“线程类”,可以创建多个“线程对象”,每个线程对象都可以独立运行。


学习目标总结:

01.能够辨别程序中异常和错误的区别
1).错误:Error – XxxxxxError
2).异常:Exception – XxxxxxxException

02.说出异常的分类
Exception:
|–RuntimeException:(运行时异常)
|–其它异常(编译期异常)

03.说出虚拟机处理异常的方式

        1).JVM执行到有异常的代码;
		2).JVM会识别出这种异常;
		3).JVM会到类库中找到描述这种异常的“异常类”--JVM为每种异常情况都定义了“异常类”。并创建异常对象;
		4).JVM会到代码中查看我们的代码是否“捕获”这种异常:
				否:JVM向控制台打印异常信息,并结束程序;【之前的情况】
				是:JVM会执行“异常处理代码-catch”--【今天讲的】

04.列举出常见的三个运行期异常

1).NullPointerException
2).ArrayIndexOutOfBoundsException
3).ArithmaticException(数学异常)int a = 10 / 0;

05.能够使用try…catch关键字处理异常

try{
		//可能出现异常的代码
	}catch(异常类名 变量名){
		//如果try中出现了“异常类名”的异常,会执行这里。
	}

06.能够使用throws关键字处理异常

main(){
	}
	public static void show() throws NullPointerException{
	}

07.能够自定义异常类

class AgeException extends RuntimeException{
		public AgeException(){
		}
		public AgeException(String msg){
		}
	}

08.能够处理自定义异常类

class Student{
	private int age;
	public void setAge(int age){
		if(age < 15 || age > 50){
			throw new AgeException("年龄错误!");
		}
		this.age = age;
	}
}

09.说出进程的概念

1).什么是进程:操作系统中一个独立运行的程序;

10.说出线程的概念

1).什么是线程:线程是由进程创建的,可以独立运行的代码,与主线程同时运行。

11.能够理解并发与并行的区别

1).并行:指两个或多个事件在同一时刻发生(同时发生)。 2).并发:指两个或多个事件在同一个时间段内发生。

12.能够开启新线程
1).制作线程:

class MyThread extends Thread{
			public void run(){
				....
			}
		}

2).启动线程:

MyThread t = new MyThread();
		t.start();
		//主线程会继续向下
		....

猜你喜欢

转载自blog.csdn.net/AdamCafe/article/details/88878476