异常
Error和Exception





捕获和抛出异常

package exception;
public class Demo01 {
public static void main(String[] args) {
int a=1;
int b=0;
try {
System.out.println(a/b);
}catch (ArithmeticException e){
System.out.println("除数不能为0");
}finally {
System.out.println("finally");
}
System.out.println("====================");
try {
System.out.println(a/b);
}catch (Error e){
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
}
System.out.println("====================");
try {
new Demo01().test(1,0);
} catch (ArithmeticException e){
e.printStackTrace();
}
System.out.println("====================");
}
public void test(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();
}
}
}
自定义异常及经验小结


package exception;
public class MyException extends Exception{
private int detail;
public MyException(int a){
this.detail = a;
}
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
package exception;
public class Test {
static void test(int a) throws MyException {
System.out.println("传递的参数为"+a);
if(a>10){
throw new MyException(a);
}
System.out.println("OK");
}
public static void main(String[] args) {
try{
test(1);
}catch (MyException e){
System.out.println("MyException=>"+e);
}
try{
test(11);
}catch (MyException e){
System.out.println("MyException->"+e);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?