package cd_one.code13;
import cd_one.code11.exer3.BelowZeroException;
public class ThrowTest {
public static void main(String[] args) {
Student s1 =new Student();
try {
s1.regist(10);
s1.regist(-10);//BelowZeroException
System.out.println(s1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Student{
private int id;
public void regist(int id) throws Exception {
if(id > 0){
this.id = id;
}else{
throw new BelowZeroException();
}
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
'}';
}
}
自定义一个小于零的异常
package cd_one.code13;
public class BelowZeroException extends Exception{
static final long serialVersionUID = -33875169948L;
public BelowZeroException() {
}
public BelowZeroException(String name) {
super(name);
}
public BelowZeroException(String message, Throwable cause) {
super(message, cause);
}
}
结果
多异常处理
package cd_one.code13;
public class App9_2 {
public static void main(String[] args) {
int[] a = {1,2,3,4};
for (int i = 0; i < 5; i++) {
try {
System.out.print("a[" + i +"]/" + "=" + (a[i]/i));
}catch(ArrayIndexOutOfBoundsException e){
System.out.print("捕获到了数组下标结异常");
}catch(ArithmeticException e){
System.out.print("异常类名称是:" + e);
}catch (Exception e) {
System.out.println("捕获" + e.getMessage() +"异常!");
} finally {
System.out.println(" finally i = " + i);
}
}
System.out.println("继续!!!!!");
}
}
运行结果
异常类名称是:java.lang.ArithmeticException: / by zero finally i = 0
a[1]/=2 finally i = 1
a[2]/=1 finally i = 2
a[3]/=1 finally i = 3
捕获到了数组下标结异常 finally i = 4
继续!!!!!
抛出异常
package cd_one.code13;
//使用throw语句在方法内跑出异常,并在同意方法内进行相应的异常处理
public class App9_3 {
public static void main(String[] args) {
int a = 5,b= 0;
try {
if(b == 0) {
throw new ArithmeticException(); //抛出异常
}else{
System.out.println(a + " / " + b + " = " + a/b); //若不抛出,则运行
}
} catch (ArithmeticException e) {
System.out.println("异常:" + e +"被抛出了!");
e.printStackTrace(); //输出当前对象的堆栈使用轨迹
}
}
}
自定义异常类
package cd_one.code13;
class CircleExption extends Exception{
double radius;
CircleExption(double radius) {
this.radius = radius;
}
@Override
public String toString() {
return "半径r=" + radius + "不是一个正数";
}
}
class Circle{
private double radius;
public void setRadius(double radius) throws CircleExption{
if(radius < 0){
throw new CircleExption(radius);
}else{
this.radius = radius;
}
}
public void show(){
System.out.println("圆面积 = "+ 3.14 * radius * radius);
}
}
public class App9_8 {
public static void main(String[] args) {
Circle cir = new Circle();
try {
cir.setRadius(-2.0);
} catch (CircleExption e) {
System.out.println("自定义异常:"+e.toString()+"");
}
cir.show();
}
}
自定义异常:半径r=-2.0不是一个正数
圆面积 = 0.0