Java基础之异常处理操作示例
本文实例讲述了Java基础之异常处理操作。分享给大家供大家参考,具体如下:
示例代码:
publicclassExecDemo{
publicstaticvoidmain(String[]args){
int[]nums=newint[4];
System.out.println("beforetheexception:");
try{//try代码块trycatch代码块可以嵌套
try{
nums[7]=10;//数组越界
System.out.println("noexception:");
}catch(ArithmeticExceptione){
e.printStackTrace();
}
}catch(ArithmeticExceptione){//catch代码块多个catch块
e.printStackTrace();//打印异常信息
}catch(ArrayIndexOutOfBoundsExceptione){//捕获数组越界错误捕获子类异常
e.printStackTrace();
}catch(Throwablee){//捕获超类异常Throwable是所有异常的超类
e.printStackTrace();
}
System.out.println("aftertheexception");
}
}
抛出异常:
publicclassThrowDemo{
publicstaticvoidmain(String[]args){
try{
System.out.println("beforethrow:");
thrownewArithmeticException();//throw关键字抛出一个ArithmeticException()异常(手动抛出异常)
}catch(ArithmeticExceptione){//捕获异常
System.out.println("exceptioncaught:");
}
System.out.println("aftertry{}catch{}:");
}
}
重新抛出异常:
classRethrow{
publicstaticvoidgenException(){
int[]numer={2,4,6,8,10,12};
int[]demon={2,0,3,4,0};
for(inti=0;i
throws语句:一个方法产生自己不做处理的异常,用throws抛出到外层(谁调用,谁处理异常)
publicclassThrowsDemo{
publicstaticcharprompt(Stringstr)throwsjava.io.IOException{//prompt()方法产生自己不做处理的IOException异常,抛出到外层,谁调用谁处理异常
System.out.print(str+":");
return(char)System.in.read();
}
publicstaticvoidmain(String[]args){
charch;
try{
ch=prompt("enteraletter");//prompt()可能抛出异常,
}catch(java.io.IOExceptione){//捕获prompt()抛出的异常
System.out.println("IOExceptionoccurred");
ch='x';
}
System.out.println("youpressed:"+ch);
}
}
可以用一个catch()捕获多个异常:
try{
}
catch(ArithmeticException|ArrayIndexOutOfBoundsExceptione){//同时捕获多个异常
}
自定义异常:
classNonIntResultExceptionextendsException{//自定义异常继承子Exception
intn,d;
NonIntResultException(inti,intj){
n=i;
d=j;
}
publicStringtoString(){
return"resultof"+n+"/"+d+"isnon-integer.";
}
}
publicclassCustomExceptionDemo{
publicstaticvoidmain(String[]args){
intnumer[]={4,8,15,32,64,127,256,512};
intdenom[]={2,0,4,4,0,8};
for(inti=0;i
更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。