java异常处理(二)
异常声明:为了让别人知道你的代码有异常,做出详细的异常声明
class ExceptionTest {
int[] show(int x) throws NegativeArraySizeException {
int[] a = new int[x];
for(int i = 0 ; i < a.length ; i++){
a[i] = i + 1;
}
return a;
}
}
public class ExceptionDemo {
public static void main(String[] args){
try {
int[] a = new ExceptionTest().show(-1);
for(int i = 0 ; i < a.length ; i++){
System.out.println(a[i] + " ");
}
} catch (NegativeArraySizeException e) {
// TODO: handle exception
System.out.println("数组长度不能为负数");
}
}
}
class ExceptionTest {
int[] show(int x) throws NegativeArraySizeException,ArrayIndexOutOfBoundsException {
int[] a = new int[x];
for(int i = 0 ; i < a.length ; i++){
a[i] = i + 1;
}
if(x >= 5)
a[a.length] = 1;
return a;
}
}
public class ExceptionDemo {
public static void main(String[] args){
try {
int[] a = new ExceptionTest().show(5);
for(int i = 0 ; i < a.length ; i++){
System.out.println(a[i] + " ");
}
} catch (NegativeArraySizeException e) {
// TODO: handle exception
System.out.println("数组长度不能为负数");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组长度超出了定义的范围");
}
}
}
自定义异常
函数内抛出了异常,在函数上必须声明异常,也就是使用了throw必须要使用throws
class ArrayZeroException extends Exception{
ArrayZeroException(String msg){
super(msg);
}
}
class ExceptionTest {
int[] show(int x) throws ArrayZeroException,NegativeArraySizeException,ArrayIndexOutOfBoundsException {
if(x == 0)
throw new ArrayZeroException("数组的长度不能为零");
int[] a = new int[x];
for(int i = 0 ; i < a.length ; i++){
a[i] = i + 1;
}
if(x >= 5)
a[a.length] = 1;
return a;
}
}
public class ExceptionDemo {
public static void main(String[] args){
try {
int[] a = new ExceptionTest().show(0);
for(int i = 0 ; i < a.length ; i++){
System.out.println(a[i] + " ");
}
} catch (NegativeArraySizeException e) {
// TODO: handle exception
System.out.println("数组长度不能为负数");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组长度超出了定义的范围");
}catch (ArrayZeroException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
throws和throw的区别
throws使用在函数上
throw使用在函数内
throws后面跟着的是异常类,可以跟多个,用逗号隔开
throw后面跟着的是异常对象