前言:
异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的。
异常发生的主要因素:
1、用户输入非法因素;
2、打开的文件不存在的时候;
3、网络通信时链接中断
4、JVM(java虚拟机)溢出
常见的异常类型:
ArithmeticException 算数错误情形(如除数为0时)
ArrayIndexOutOfBoumdsException 数组下标越界
NullPointeException 尝试访问null对象成员(空指针)
ClassNotFoundException 不能加载所需的类
InputMismatchException 输入类型异常
IllegalArgumentException 方法接收到非法参数
ClassCastException 对象强制类型转换异常
NumberFormatException 数字格式转换异常,如把”abc”转换成数字
PS:Exception是所有异常的父类
处理异常的方法:
if else 方法:
以处理输入类型不匹配异常为例:
public static void main(String[] args)
{
//创建Scanner对象,此时需导包 import java.util.Scanner;
//快捷键是Shift+Alt+o
Scanner input = new Scanner(System.
System.out.println("请输入数字");
if(input.hasNextInt()) //判断是否为指定的类型
{
int num = input.nextInt();
System.out.println("输入的数字为:"+num);
}
else
{
System.out.println("您输入的类型不匹配!");
//扫描器已经关闭,此时必须重新定义一个新的键盘输入
input= new Scanner(System.in);
}
}
if else处理异常的缺点:
1、代码臃肿,加入大量异常情况判断和处理代码。
2、程序员把相当多的精力放在了处理异常代码上,放在了“堵漏洞”上,减少了编写业务代码的时间,影响开发效率。
3、难以举出所有的异常情况,程序依旧不健壮。
4、影响代码的可读性,加大日后维护代码的难度。
try–catch-finally处理异常
public static void main(String[] args)
{
//创建Scanner对象,此时需导包 import java.util.Scanner;
//快捷键是Shift+Alt+o
Scanner input = new Scanner(System.in);
System.out.println("请输入数字");
try
{
int num = input.nextInt();
System.out.println("您输入的数字是:"+num);
}
catch(InputMismatchException e)
{
System.out.println("输入的类型不匹配!!!");
e.printStackTrace(); //打印出异常情况
}
finally
{
//无论是否异常,finally代码块都会执行
System.out.println("谢谢使用!");
}
}
注意事项:
1、catch不能独立于try存在
2、try后不能既没有catch块也不能没有finally代码块
3、在try、catch后添加finally代码块并非强制性要求
4、try、catch、finally块之间不能添加任何代码
5、即使在try代码块、catch代码块、中存在return语句,finally代码块也会执行,唯一不执行的情况是在此之前执行了System.exit(0)。
throw和throws关键字
throws是将异常抛给调用者处理,用在方法后面,一次可以抛出多个异常,中间使用逗号隔开。
throw是自定义异常,使用在方法里面
例如自定义一个性别异常类:
public class student
{
public void setSex(String sex) throws SexException
{
if (sex.equals("男") || sex.equals("女"))
{
this.sex = sex;
}
else
{
//自定义异常必须编写自定义异常类
throw new SexException("有个性!没人性?");
}
}
}
/*
* 自定义异常类必须继承Exception类
*/
public class SexException extends Exception {
private static final long serialVersionUID = 1L;
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
}
}