1,常见异常
- ArrayIndexOutOfBoundsException,数组下标越界异常
- NullPointerException,空指针异常
- ArithmeticException,算术异常
- ClassCastException,类型转换异常
2,throws与throw
- throws在方法声明处,throw在方法中
- throws后面跟异常类名,throw后跟异常对象
- throws是处理异常,throw是手动产生异常
package ExceptionDemo;
/*
* 处理异常的两种方式
* throws抛出异常,try/catch手动捕捉异常
* throw是手动产生异常
*/
public class ThrowAndThrows {
public static void main(String[] args) {
show();
}
public static void show(){
int i = 10;
int b = 2;
int c = i/b;
if (b == 2) {
try {
throw new Exception();//认为添加异常
} catch (Exception e) {
// TODO: handle exception
System.out.println("b不能为2");
}
}
}
}
3,手动抛出自定义异常
package ExceptionDemo;
public class CustomDemo {
public static void main(String[] args) {
int a=10;
if (a==10) {
try {
throw new Custom1("a不能为10");//手动抛出自定义异常
} catch (Custom1 e) {
e.printStackTrace();
}
}
}
}
class Custom1 extends Exception{
public Custom1(String message) {
//将信息传递给Exception
super(message);
}
}