JAVA 异常学习

 

目录

一.try-catch

1.有了异常,加try-catch和不加try-catch的区别

2.try-catch-finally

2.try-catch-catch-finally

3.如何让finally不输出

4.在语句中加入return

二.Throws和Throw

1.区别

2.例子

三.自定义异常

1.步骤

2.例子1

 3.例子2

四.一些面试题

1.列出至少五种以上常见异常

2.列出异常的五个关键字

3.throws和throw的区别

4.final与finally和finalize区别?

5.finally什么时候不执行。

6.exception与error的区别。


一.try-catch

1.有了异常,加try-catch和不加try-catch的区别

1)没加try-catch

package com.gongsi.cn.oa.work805.test1;

import java.util.Scanner;

public class BaiDuServer {
	public static void main(String[] args) {
		System.out.println("百度服务器已经启动");
		System.out.println("百度服务器给成千上万人提供服务");
		Scanner input=new Scanner(System.in);
		System.out.print("请客户输入任意字符:");

			int i=input.nextInt();
			System.out.println("您输入的信息是:"+i);
			System.out.println("百度服务器帮你处理信息");
	}

}

 出现异常后不会再执行

2)加try-catch

package com.gongsi.cn.oa.work805.test1;

import java.util.Scanner;

public class BaiDuServer {
	public static void main(String[] args) {
		System.out.println("百度服务器已经启动");
		System.out.println("百度服务器给成千上万人提供服务");
		Scanner input=new Scanner(System.in);
		System.out.print("请客户输入任意字符:");
		try {//试图
			int i=input.nextInt();
			System.out.println("您输入的信息是:"+i);
			System.out.println("百度服务器帮你处理信息");
		} catch (Exception e) {//捕捉
			System.out.println("异常处理,治疗!!!");
		}
		System.out.println("百度服务器继续运行做其他事情......");
	}

}

捕捉到异常后,执行catch里面的语句,然后继续按顺序执行

 

2.try-catch-finally

package com.gongsi.cn.oa.work805.test2;

import java.util.Scanner;

public class TestException {
	public static void main(String[] args) {
		try {//捕捉异常
			Scanner scanner=new Scanner(System.in);
			System.out.println("开煤气....");
			System.out.println("炒菜");
			System.out.print("我炒焦了吗?输入0就是焦了:");
			int b=scanner.nextInt();
			int r=8/b;
			
			System.out.println("菜很好吃,给人吃!");
			//System.exit(0);
			//return;
		} catch (Exception e) {//有异常时执行
			e.printStackTrace();
			System.out.println("用来喂猪");
			//return;
			//System.exit(0);
			
		}finally {//都会执行
			System.out.println("关煤气!");//finally什么时候不被执行 System.exit(0);
		}
		//System.out.println("return结束方法以后的语句,这里执行不到");
	}

}

 有异常时:

 

 没有异常时:

 由此可见,finally里的语句无论有没有出现异常,都会被执行。(什么时候不会被执行?下面会讲到)

 

2.try-catch-catch-finally

package com.gongsi.cn.oa.work805.test2;

import java.util.InputMismatchException;
import java.util.Scanner;

public class TestException2 {
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		try {
			System.out.println("去医院看病");
			System.out.println("医生:你有什么病吗?");
			System.out.print("病人:");
//			String s="null";
//			System.out.println(s.length());
			
			int b=scanner.nextInt();
			int r=8/b;
			System.out.println("没病啊");
		}catch (ArithmeticException ae) {
			ae.printStackTrace();
			System.out.println("医生处理ArithmeticException类型的疾病");
		}catch (InputMismatchException ime) {
			ime.printStackTrace();
			System.out.println("医生处理InputMismatchException类型的疾病");
		}catch (Exception e) {
			System.out.println("我病了.....");
			System.out.println("捕捉到不知道名字的病,医生不懂处理....");
		}finally {
			System.out.println("从医院出来...");
		}
	}

}

 

 

 try catch catch finally 相当于多态

 

 

3.如何让finally不输出

finally不管是否发生异常,都会被执行。作用:用于关资源:关闭数据库连接,关闭文件输入输出流。 finally唯一不被执行:exit(0);exit(1); 遇到return 语句, finally也被执行的。

package com.gongsi.cn.oa.work805.test2;

import java.util.Scanner;

public class TestException {
	public static void main(String[] args) {
		try {//捕捉异常
			Scanner scanner=new Scanner(System.in);
			System.out.println("开煤气....");
			System.out.println("炒菜");
			System.out.print("我炒焦了吗?输入0就是焦了:");
			int b=scanner.nextInt();
			int r=8/b;
			
			System.out.println("菜很好吃,给人吃!");
			System.exit(0);
			//return;
		} catch (Exception e) {//有异常时执行
			e.printStackTrace();
			System.out.println("用来喂猪");
			//return;
			System.exit(0);
			
		}finally {//都会执行
			System.out.println("关煤气!");//finally什么时候不被执行 System.exit(0);
		}
		//System.out.println("return结束方法以后的语句,这里执行不到");
	}

}

 

发现finally那句“关煤气”已经不会被执行

 

4.在语句中加入return

return :下一个语句将不会被执行

package com.gongsi.cn.oa.work805.test2;

import java.util.Scanner;

public class TestException {
	public static void main(String[] args) {
		try {//捕捉异常
			Scanner scanner=new Scanner(System.in);
			System.out.println("开煤气....");
			System.out.println("炒菜");
			System.out.print("我炒焦了吗?输入0就是焦了:");
			int b=scanner.nextInt();
			int r=8/b;
			
			System.out.println("菜很好吃,给人吃!");
			//System.exit(0);
			return;
		} catch (Exception e) {//有异常时执行
			e.printStackTrace();
			System.out.println("用来喂猪");
			//return;
			//System.exit(0);
			
		}finally {//都会执行
			System.out.println("关煤气!");//finally什么时候不被执行 System.exit(0);
		}
		System.out.println("return结束方法以后的语句,这里执行不到");
	}

}

 

 

 

 

二.Throws和Throw

1.区别

1)位置

 * throws在方法后面出现
 * throw在方法里面出现

 

2)抛出异常个数

 * throws可以抛出多个异常类型
 * throw只能抛出一个异常对象

 

3)作用

 * throws 声明该方法有可能发生异常,告诉程序员调用时候要小心,要处理。
 * throw 直接抛出一个明确的异常对象。

4)抛出异常类型

 * throws抛出类型
 * throw 抛出对象

2.例子

检查时异常(运行时异常在下面讲)

检查时异常,一定要加try catch

package com.gongsi.cn.oa.work805.test2;

import javax.swing.JOptionPane;
//检查时异常,一定要加try catch
public class TestThrow {
	public static void main(String[] args) {
		int a=8;
		int b=0;
		int r=0;
		try {
			r=div(a, b);
			System.out.println(r);
			
		} catch (Exception e) {
			e.printStackTrace();//给程序员看的,程序员看懂
			String msg=e.getMessage();//给客户看的
			System.out.println(msg);
			JOptionPane.showConfirmDialog(null, msg);
		}
	}
	
	//throws声明该方法有可能发生异常,告诉程序员调用时候要小心,要处理
	
	public static int div(int a,int b) throws DivNotZeroException{
		if (b==0) {
			throw new DivNotZeroException("除数不能为0");
		}
		int result=a/b;
		return result;
	}

}

 

三.自定义异常

1.步骤

1)自定义一个异常类,继承Exception(检查异常)或者继承RunTimeException(运行时异常)

2)编写异常的构造方法,继承父类的构造方法

3)在方法后面加throws 异常类

4)在方法内部new一个异常类对象并且抛出Throw

2.例子1

运行时异常  继承父类RuntimeException

1)自定义一个异常类

package com.gongsi.cn.oa.work805.test3;
//运行时异常 继承父类RuntimeException
public class DivNotZeroException extends RuntimeException {

	public DivNotZeroException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public DivNotZeroException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

	public DivNotZeroException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public DivNotZeroException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public DivNotZeroException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}
	

}

2)构造方法生成:

3)在方法后面加throws 异常类 在方法内部new一个异常类对象并且抛出Throw

 

package com.gongsi.cn.oa.work805.test3;
//运行时异常,可以不加try catch
import javax.swing.JOptionPane;

public class TestThrow {
	public static void main(String[] args) {
		int a=8;
		int b=0;
		int r=0;
	
			r=div(a, b);
			System.out.println(r);
			

	}
	
	//throws声明该方法有可能发生异常,告诉程序员调用时候要小心,要处理
	
	public static int div(int a,int b) throws DivNotZeroException{
		if (b==0) {
			throw new DivNotZeroException("除数不能为0");
		}
		int result=a/b;
		return result;
	}

}

 可以不加try catch,这样运行之后才报错

 3.例子2

 自定义异常 性别只能为男或者女 年龄在1~150之间

package com.gongsi.cn.oa.work805.test4;
//自定义异常 性别只能为男或者女 年龄在1~150之间
public class Student {
	private String name;
	private String sex;
	private String address;
	private int age;
	public Student(String name, String sex, String address, int age) {
		super();
		this.name = name;
		this.sex = sex;
		this.address = address;
		this.age = age;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) throws AgeException{
		if (age<1||age>150) {
			throw new AgeException("年龄只能是1~150之间");
			
		}
		this.age = age;
	}
	public Student() {
		super();
	}
	public Student(String name, String sex, String address) {
		super();
		this.name = name;
		this.sex = sex;
		this.address = address;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	//声明该方法可能存在异常,调用者小心,处理
	public void setSex(String sex) throws SexException{
		if (!(sex.equals("男")||sex.equals("女"))) {
			throw new SexException("性别只能是男或者女");//真正的抛出了一个异常对象
			
		}
		this.sex = sex;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	

}
package com.gongsi.cn.oa.work805.test4;
//自定义性别异常 
public class SexException extends Exception {

	public SexException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public SexException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

	public SexException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public SexException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public SexException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}
	

}
package com.gongsi.cn.oa.work805.test4;
//自定义年龄异常
public class AgeException extends Exception {

	public AgeException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public AgeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

	public AgeException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public AgeException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public AgeException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

}
package com.gongsi.cn.oa.work805.test4;

import javax.swing.JOptionPane;
//自定义异常 性别只能为男或者女 年龄在1~150之间
public class TestStudent {
	public static void main(String[] args) {
		Student student=new Student();
		try {
			student.setSex("男");//当年龄出现异常时,不再执行下一个语句,也就是不再执行setAge
			student.setAge(155);
			System.out.println(student.getSex());
		} catch (SexException se) {
			se.printStackTrace();
			JOptionPane.showConfirmDialog(null, se.getMessage());
		} catch (AgeException ae) {
			ae.printStackTrace();
			JOptionPane.showConfirmDialog(null, ae.getMessage());
		}catch (Exception e) {
			JOptionPane.showConfirmDialog(null, "发生不知名异常");
		}finally {
			System.out.println("关闭资源!");
		}
		
		
		
	}

}

 

 

 

四.一些面试题

1.列出至少五种以上常见异常

1)NullPointerException 空指针异常

 

2)ClassNotFoundException "类没有"发现异常

最难发现的一个异常。也就是bin目录下的.class文件没有了,解决办法,重新编译。


3)ArrayIndexOutOfBoundsException 数组下标越界异常

 


4)ClassCastException 类转换异常


5)ArithmeticException 数学异常

 

 


6)InputMismatchException 输入不匹配异常

 

 

2.列出异常的五个关键字

   try catch finally throw throws

3.throws和throw的区别

 上面已经提到了

4.final与finally和finalize区别?

  1)final:最终的,最终版的,用于修饰变量就变成常量
      修饰类就是最终版的类,不给其它类继承。
      修饰反复就是最终版的方法,不给子类重写
  2) finally 是异常处理中的关键字,表示无论是否发生异常,都要执行的语句块,唯一不执行的    情况就exit(0),exit(1)
  3)finalize;是Object中的一个方法,用于给垃圾回收器回收前做资源释放处理。

5.finally什么时候不执行。

exit(0),exit(1)

6.exception与error的区别。

 1) Error:错误,是非常严重的问题,没办法处理,不要试图去解决这些问题,例如内存溢出
 2)Exception: 已检查异常,程序已经经过检查,但是由于外界因素导致仍然不可避免的问题,要求开发者必须未雨绸缪的处理这些异常
 3) RuntimeException:未检查异常,是由于程序员没有细致检查程序导致的异常,这种异常编译器把所有责任推给程序员,即编译器不会帮你检查,也不要求你必须处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值