电脑

当前位置 /首页/游戏数码/电脑/列表

Java常见异常和错误

总结JAVA常见的异常和错误。

操作方法

(01)1、 在某一路径下执行编译好的class文件出错。异常如下:E:liwy>java Test98Exception in thread "main" assDefFoundError: Test98如果出现了以上错误提示,常见问题有如下两种:1 大小写写错了, 2 路径不正确。

Java常见异常和错误

(02)2、数组错误,访问不存在的数组,数组超出绑定,代码如下:public class ArrayDemo{public static void main(String args[]){int array[] = null; //声明数组array = new int[3]; //为数组开辟空间,大小为3for(int i=0;i<th;i++){tln("array["+i+"]="+i);}//访问数组没有开辟的下标,这时会报异常tln("array[3]="+array[3]);}}异常如下:array[0]=0array[1]=1array[2]=2Exception in thread "main" yIndexOutOfBoundsException: 3at ()以上就是数组的索引超出绑定,就是表示数组越界。

(03)3、某个类没有实例化,访问类属性时,出现空指针异常class Person{String name ;  // 声明姓名属性int age ;   // 声明年龄属性public void tell(){ // 取得信息tln("姓名:" + name + ",年龄:" + age) ;}};public class ClassDemo03{public static void main(String args[]){Person per = null ;  // 声明对象//per = new Person() ; // 实例化对象 = "张三" ;  // 为姓名赋值 = 30 ;   // 为年龄赋值() ;   // 调用方法,打印信息}};异常如下:Exception in thread "main" PointerExceptionat ()

(04)4、错误的多态,出现异常class A{     // 定义类Apublic void fun1(){  // 定义fun1()方法tln("A --> public void fun1(){}") ;}public void fun2(){1() ;  // 调用fun1()方法}};class B extends A{public void fun1(){  // 此方法被子类覆写了tln("B --> public void fun1(){}") ;}public void fun3(){tln("B --> public void fun3(){}") ;}};public class PolDemo03{public static void main(String asrgs[]){A a = new A() ;   // 实例化了一个父类对象B b = (B)a ;  // 发生了向下转型关系1() ;2() ;3() ;}};异常如下:Exception in thread "main" sCastException: Aat ()

(05)5、两个数字相除,被除数为0,出现异常public class ExceptionDemo01{public static void main(String args[]){tln("********** 计算开始 ***********") ;int i = 10 ;  // 定义整型变量int j = 0 ;   // 定义整型变量int temp = i / j ; // 此处产生了异常tln("两个数字相除的结果:" + temp) ;tln("********** 计算结束 ***********") ;}};异常如下:********** 计算开始 ***********Exception in thread "main" hmeticException: / by zeroat (:6)

(06)6、两个数字相除,输入两个参数,分别为字母a 和b,出现异常,数字格式化出问题public class ExceptionDemo04{public static void main(String args[]){tln("********** 计算开始 ***********") ;int i = 0 ;  // 定义整型变量int j = 0 ;   // 定义整型变量try{String str1 = args[0] ;  // 接收第一个参数String str2 = args[1] ;  // 接收第二个参数i = eInt(str1) ; // 将第一个参数由字符串变为整型j = eInt(str2) ; // 将第二个参数由字符串变为整型int temp = i / j ; // 此处产生了异常tln("两个数字相除的结果:" + temp) ;tln("----------------------------") ;}catch(ArithmeticException e){ // 捕获算术异常tln("出现异常了:" + e) ;}tln("********** 计算结束 ***********") ;}};异常如下:********** 计算开始 ***********Exception in thread "main" erFormatException: For input string: "a"at nputString()at eInt()at eInt()at (

(07)7、两个数字相除,输入两个参数,如果两个参数什么也不输入,出现异常,数组超出绑定。异常如下:********** 计算开始 ***********Exception in thread "main" yIndexOutOfBoundsException: 0at (:7)

(08)7、assert断言的使用,当断言结果不对出现异常。public class Test{public static void main(String args[]){int i[] = {1,2,3};   // 数组长度为3assert th==0;  // 此处断言数组长度为0}}异常如下:D:d代码>java -ea TestException in thread "main" rtionErrorat (:5)l 断言需要在运行时需要加上“-ea”,如上java –ea 类名。

TAG标签:JAVA #