异常
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nodp9xok-1606719385330)(C:\Users\11096\Desktop\acadc9cad734329e60e788a06fd7420.png)]
try catch finally throw throws
package com.breet.exception;
public class Test {
public static void main(String[] args) {
int a=1;
int b=0;
//假设要捕获多个异常:从小到大!
try {//try是监控区域
System.out.println(a/b);
}catch (Error e){
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
} catch (Throwable e){//catch捕获异常 catch(想要捕获的异常类型)Throwable是最大的异常
System.out.println("Throwable");
}finally {//处理善后工作
System.out.println("finally");
}
//finally可以不要,假设IO,资源,关闭!
}
}
package com.breet.exception;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.w3c.dom.ls.LSOutput;
public class Test2 {
public static void main(String[] args) {
Test2 test2=new Test2();
//ctrl+alt+t
try {
test2.test(2,0);
} catch (ArithmeticException e) {
System.out.println("程序发生异常,除数b不能为0");//打印错误的栈信息
} finally {
System.out.println("finally");
}
}
//假设方法中处理不了这个异常,则主动向上抛出这个异常
public void test(int a,int b)throws ArithmeticException {
if(b==0){
throw new ArithmeticException();
}
else {
System.out.println(a/b);
}
}
}
package com.breet.exception.demo02;
//自定义的异常类
public class MyException extends Exception {
//传递数字>10
private int detail;
public MyException(int a) {
this.detail=a;
}
//toString:异常的打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
package com.breet.exception.demo02;
public class Test3 {
public static void main(String[] args) {
try{
test(11);
}catch (MyException e){
System.out.println("Myexception="+e);
}
finally {
System.out.println("finally");
}
}
//可能会存在异常的方法
static void test(int a) throws MyException{
if(a>10){
throw new MyException(a);
}
else{
System.out.println(a);
}
}
}
throw new MyException(a);
}
else{
System.out.println(a);
}
}
}