9.1 异常概述
异常可能由程序员没有想到的情况超出范围内
例题代码如下
public class Nineone {
public static void main(String[] args) {
// TODO Auto-generated method stub
int result =3/0;
System.out.println(result);
}
}//例题9.1
出现异常:不能被零整除,算法异常
例题代码如下
public class Nineone {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str ="lili";
System.out.println(str + "年龄是:");
int age = Integer.parselent("20L");
System.out.println(age);
}
}//例题9.2
结果如下
9.2:异常的抛出与捕获
9.2.1:抛出异常
9.2.2:捕捉异常
try{
//代码块
}catch (Exceptiontype1){
catch (xceptiontype2)
}
....
finally{
//程序代码块}
9.1代码运行结果如下
public class Nineone {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int result =3/0;
System.out.println(result);
}catch(ArithmeticException e) {
System.out.println("算法异常");
}
}
}//例题9.1
结果如下
9.2代码如下
public class Nineone {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str ="lili";
System.out.println(str + "年龄是:");
int age = Integer.parseInt("20");
System.out.println(age);
}
}//例题9.2
public class Nineone {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String str ="lili";
System.out.println(str + "年龄是:");
int age = Integer.parseInt("20L");
System.out.println(age);
}catch (Exception e) {
System.out.println("program over");
}finally {
System.out.println("程序异常");
}
}
}//例题9.2
结果如下
9.3:Java常见的异常类
常见的异常类
异常类 说明
ClassCastException 类型转换异常
ClassNotFoundException 未找到相应类异常
AritchmeticException 算术异常
ArrayIndexOutOfBoundsException 数组下标越界异常
ArrayStoreException 数组中包含不兼容的值抛出的异常
SQLException 操作数据库异常类
NullPointerException 空指针异常
NoSuchFieldException 字段未找到异常
NoSuchMethodException 方法未找到抛出的异常
NumberFormatException 字符串转换为数字抛出的异常
NegativeArraySizeException 数组元素个数为负数抛出的异常
StringIndexOutOfBoundsException 字符串索引超出范围抛出的异常
IOException 输入输出异常
IllegalAcessException 不允许访问某类异常
InstantiationException 当应用程序试图使用Class类中的newInstance()方法重创建一个类得实例,而指定的类的对象无法被实例化时,抛出该异常
EOFException 文件已结束异常
FileNotfoundException 文件未找到异常
9.4: 自定义异常
定义1个exception类继承,这就是自定义异常
括号里是传入参数,super是隐藏方法,作用是调用父类的构造方法打印出错误信息
public class MyException extends Exception { //自定义异常
public MyException (String ErrowMessage) {//输出错误方法
super(ErrowMessage);//调用父类的构造方法
}
}
//例题9.4
9.5:在方法中抛出异常
public class Tran {
static int avg(int number1,int number2) throws MyException {//调用抛到调用avg的地方
if(number1<0||number2<0){
//System.out.println("不可以使用负数");条件判断
throw new MyException("不可以使用负数");//抛出异常给avg
}
if(number1>100||number2>100){ //判断条件
throw new MyException("不可以大于100");
}
return (number1+number2)/2;//求平均数,返回值
}
public static void main(String[] args) {//主函数调用方法
// TODO Auto-generated method stub
try {
int result = avg(102,150);
System.out.println(result);
} catch (MyException e) {
System.out.println(e);
}
}}
//例题9.5