您好,欢迎访问一九零五行业门户网

Java中定义自定义异常的方法是什么?

一、异常分为哪几种异常分为两种,分别是编译异常和运行时异常。
编译时异常
都是exception类及其子类
必须显示处理,否则程序就会发生错误,无法通过编译
运行时异常
都是runtimeexception类及其子类
无需显示处理,也可以和编译时异常一样处理
package com.xxgc.chop5_2.test; public class exceptiondemo { public static void show4(){ //把字符串转换int类型 string a="张三"; int b=integer.parseint(a);//numberf } //异常抛出 public static void show3() throws classnotfoundexception { class.forname("student"); } public static void show2(){ //运行时异常:程序运行的时候出现的异常,可以try //编译时异常(非运行时异常):必须try catch 或者向上抛出 try { class.forname("student"); }catch (classnotfoundexception e){ e.printstacktrace(); } } public static void show() { //制造一个异常,捕获异常,处理异常 try{ int []nums={1,2}; int n=10/0; int a=nums[3]; }catch (arrayindexoutofboundsexception e) { e.printstacktrace(); system.out.println("数组下标出错了"); }catch (exception e){ e.printstacktrace(); system.out.println("出错了"); }finally { //最终最后都要之心的代码,一般完成资源释放工作 system.out.println("最终的!!!"); } } public static void main(string[] args) { //trows:向上抛出异常,抛给方法的调用者 //show3()方法向上抛出了异常,需要main方法解决 //1.main方法解决了 //2.main没解决完,继续向上抛,jvm(java虚拟机)解决 try { show3(); } catch (classnotfoundexception e) { throw new runtimeexception(e); } }}
二、自定义异常1.首先新建一个类这个类是自定义异常的类,首先我们进行继承idea的runtimeexception,其次建立有参和无参的方法。
代码如下(示例):
package com.xxgc.ch06.po; public class myexception extends runtimeexception{ public myexception(){ } public myexception(string s){ super(s); } }
2.测试类下面新建一个测试类,main方法和shou方法。在shou方法里定义一个int类型的a,进入if判断a是否异常。
代码如下(示例):
package com.xxgc.ch06.test; import com.xxgc.ch06.po.myexception; public class throwdemo { public static void show(){ //如果a>10,抛出自己的异常 int a=13; if (a>10){ try { throw new myexception("不能大于10"); }catch (myexception e){ e.printstacktrace(); system.out.println("出错啦!"+e.getmessage()); } } system.out.println("扶苏"); } public static void main(string[] args) { show(); }}
该处使用的idea软件。
以上就是java中定义自定义异常的方法是什么?的详细内容。
其它类似信息

推荐信息