零异常
package cn.cast;
import java.util.TreeMap;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class HelloWorld {
public static void main(String[] args) {
Demo d = new Demo();
try {
int x = d.div(10, 0);
System.out.println(x);
} catch (ArithmeticException e) {
System.out.println("除数为零了");
}
}
}
class Demo {
public int div(int a,int b) {
return a / b;
}
}
超出边界异常
package cn.cast;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class HelloWorld {
/**
* @param args
* 安卓都是try{}catch(Exception e){}客户端
* EE都是从底层往上抛 服务端
*/
public static void main(String[] args) {
demo1();
int a = 10;
int b = 0;
int[] arr = {11,22,33};
try {
System.out.println(arr[5]);
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("除数为零了");
} catch (Exception e3) {
System.out.println("出问题了");
}
System.out.println("over");
}
public static void demo1() {
int a = 10;
int b = 0;
int[] arr = {11,22,33};
try {
System.out.println(arr[5]);
arr = null;
System.out.println(arr[0]);
} catch (ArithmeticException e) {
System.out.println("除数为零了");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("出问题了");
}
System.out.println("over");
}
}
class Demo {
public int div(int a,int b) {
return a / b;
}
}
获取异常信息
public static void main(String[] args) throws FileNotFoundException {
try {
System.out.println(1/0);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
}
finnaly的用法
try {
System.out.println(1/0);
} catch (Exception e) {
System.out.println("catch执行了吗");
return;
} finally {
System.out.println("finally执行了吗");
}
finnaly里面return影响
public static void main(String[] args) {
System.out.println(getNum());
}
public static int getNum() {
int x = 10;
try {
System.out.println(10 / 0);
return x;
} catch (Exception e) {
x = 20;
return x;
}finally {
x = 30;
System.out.println("执行了吗");
}
}
自定义异常
package cn.itcast.bean;
public class AgeOutOfBoundsException extends Exception {
public AgeOutOfBoundsException (){
super();
}
public AgeOutOfBoundsException (String message){
super(message);
}
}
public void setAge(int age) throws AgeOutOfBoundsException {
if(age > 0 && age < 200) {
this.age = age;
}else {
throw new AgeOutOfBoundsException("年龄非法");
}
}