抛出异常:使用throw抛出异常
主讲人:王少华 QQ群号:483773664
学习目标:
1、掌握使用throw抛出异常
2、总结Java中对异常处理的二种方式
一、使用情境
当程序发生错误时,系统会自动抛出异常,这是我们上节使用的throws声明抛出异常,除此以外,Java也允许程序员自行抛出异常。自行抛出异常,使用throw语句完成。
那么什么时候程序员自行抛出异常呢?一般情况下,程序员自行抛出的异常,是由业务产生的,比如性别输和不是“男“或”女“,系统是无法自行判断这种异常的,只能由程序员来决定是否抛出。
二、语法1 throw
ExceptionInstance
三、示例
(一)书写throw异常
123456789101112 public
class
Person {
private
String name;
private
int
age;
private
String sex;
public
void
setSex(String sex)
throws
Exception {
if
(
"男"
.equals(sex)||
"女"
.equals(sex)){
this
.sex = sex;
}
else
{
throw
new
Exception(
"性别必须是:男或女"
);
}
}
}
(二) 捕获throw异常
12345678910 public
class
Test {
public
static
void
main(String[] args) {
Person person =
new
Person();
try
{
person.setSex(
"male"
);
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
1 | throw ExceptionInstance |
1 2 3 4 5 6 7 8 9 10 11 12 | public class Person { private String name; private int age; private String sex; public void setSex(String sex) throws Exception { if ( "男" .equals(sex)|| "女" .equals(sex)){ this .sex = sex; } else { throw new Exception( "性别必须是:男或女" ); } } } |
1 2 3 4 5 6 7 8 9 10 | public class Test { public static void main(String[] args) { Person person = new Person(); try { person.setSex( "male" ); } catch (Exception e) { e.printStackTrace(); } } } |
四、throw和throws的区别
使用不同:throw用于程序中抛出异常;throws用于声明在该方法内抛出了异常
使用位置不同:throw位于方法体内部,可以作为单独语句使用;throws必须跟方法参数列表后面,不能单独使用
内容不同:throw抛出一个异常对象,而且只能是一个;throws后面跟异常类,而且可以跟多个异常类。
五、throw和catch同时使用
综合前几节所讲的内容,我们对异常的处理有二种方法
在出现异常的方法内捕获并处理异常,使用try-catch-finallly,该方法的调用者不用再次捕获该异常。
该方法签名中声明抛出该异常,将该异常交给方法调用都处理.
(一)应用情境
实际应用中往往需要更复杂的处理方式:当一个异常出现的时候,单靠某个方法无法完全处理该异常,必须由几个方法才可以完全处理该异常。也就是说,异常出现的当前方法中,程序只对异常进行部分处理,还有些处理需要该方法的调用者中才能完成,所以应该再次抛出异常。
(二)示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class Cal { public String division(String stra, String strb) throws Exception{ try { int a = Integer.parseInt(stra); int b = Integer.parseInt(strb); int c = a / b; return String.valueOf(c); } catch (NumberFormatException e) { System.err.println( "数字格式异常:程序只能接受整数参数" ); return "数字格式异常" ; } catch (Exception e) { throw new Exception( "未知异常" ); } finally { System.out.println( "感谢您使用本程序!" ); } } } |
1 2 3 4 5 6 7 8 9 10 | public class Test6 { public static void main(String[] args) { Cal cal = new Cal();   ![]()
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
举报文章 请选择举报类型
内容侵权
涉嫌营销
内容抄袭
违法信息
其他
补充说明 0/200 上传截图 格式支持JPEG/PNG/JPG,图片不超过1.9M 如有误判或任何疑问,可联系 「小助手微信:cto51cto」申诉及反馈。
我知道了
|