java使用throw和try-catch机制来处理异常。

In this Java tutorial, I’m going to tell you how to write code that declares to throw exceptions. This involves in using the throw and throws keywords together.

throw如何引发异常?

package ff;public class Engineer {protected int age;public void setAge(int age) {this.age = age;}}

我们要确保工程师的年龄始终在有效范围内,例如 在21到59之间。为此,我们可以检查参数age并在超出范围时引发异常。 因此,我们像下面一样更新setAge()方法:

package ff;public class Engineer {protected int age;public void setAge(int age) {if (age < 21 || age > 59) {throw new IllegalArgumentException("Invalid age");}this.age = age;}}

Here, the throwkeyword is used to throw a new exception object if the passed-in parameter has invalid value. When the statement started by the throw keyword gets executed, the current method stops its execution and control returned to the caller code which can have an exception handler.

The following is a test program that uses try-catch structure to handle the above exception:

package Bean;public class Engineer {protected int age;public void setAge(int age) {if (age < 21 || age > 59) {//          抛出一个异常throw new IllegalArgumentException("Invalid age");}this.age = age;}public static void main(String[] args) {try {Engineer engineer = new Engineer();engineer.setAge(12);}
//        捕获异常catch (IllegalArgumentException e) {//输出控制台System.out.println(e);//错误控制台System.err.println(e);}}
}

抛出一个异常:throw new IllegalArgumentException("Invalid age");

该程序尝试通过从命令行参数传递age来创建一个新的Engineer对象。 注意,在catch块中,我们使用System.err静态类打印出异常对象。 它代表错误控制台,它不同于System.out静态类所代表的输出控制台。

上面的示例向您展示了如何使用throw 关键字在代码中引发异常

throws指定要在方法中引发的异常

我们如何知道方法是否可以抛出异常,如果可以抛出异常,那么它可以抛出哪些异常?

通过在方法签名中查找throws子句,可以知道该方法是否可以抛出异常,以及可以抛出哪种异常?

如果调用使用throws关键字定义的方法,就必须处理调用该方法可能出现的异常

throws关键字用于定义方法是否抛出异常
throw用于抛出异常

example:

    public int divide(int a, int b) throws Exception {if (b == 0) {throw new Exception("Cannot be devided by zero");}return a / b;}

throw和throws的一些使用规则

Remember the following rules:

  • If code in a method throws checked exceptions, the method must specify those exceptions in the throws clause.
  • Unchecked exceptions are not required to be caught or declared.
  • The exceptions specified in the throws clause can be broader than the ones can be thrown in the method’s body. Here’s an example:
    public void deleteDir(String path) throws IOException {if(path==null){throw new FileNotFoundException();}}

Here, code in the method can throw FileNotFoundException but the method declares to throw IOException. This is possible because IOException is the parent class of FileNotFoundException.

  • A method can declare to throw exceptions although its code doesn’t throw any exceptions. This is possible because the code can throw exceptions when it involves in the future. Here’s an example:
public void encryptFile(String path) throws IOException {// no exceptions thrown here...
}
  • Constructors can throw exceptions and declare to throw exceptions just like normal methods.
  • We can also specify exceptions can be thrown by methods in an interface.

抛出异常关键字throw与定义异常关键字throws相关推荐

  1. java 异常处理的关键字_java异常,异常处理,异常类 关键字:throws 和 throw 自定义的异常类...

    packagecn.kecheng;importjava.util.Scanner;/**异常:异常是指在程序的运行过程中所发生的不正常的情况,它会中断正在运行的程序 异常处理机制:java中通过异常 ...

  2. JAVA异常处理、自定义异常、throws关键字与throw关键字、运行时异常

    异常捕捉, try-catch语句. package YH;public class Thundering {public static void main(String[] args) {try { ...

  3. Java中关键字throw和throws的区别

    抛出异常有三种形式 throw throws 系统自动抛异常 一.系统自动抛异常 当程序语句出现一些逻辑错误.主义错误或类型转换错误时,系统会自动抛出异常:(举个栗子) public static v ...

  4. Java异常架构与异常关键字

    1. Java异常简介 Java异常是Java提供的一种识别及响应错误的一致性机制. Java异常机制可以使程序中异常处理代码和正常业务代码分离,保证程序代码更加优雅,并提高程序健壮性.在有效使用异常 ...

  5. java定义包的关键字_如何定义包,关键字是什么?

    展开全部 Java关键字及其作用 一. 关键字总览: 访问控制 private protected public 类62616964757a686964616fe59b9ee7ad9431333363 ...

  6. 22.Java之异常处理(异常介绍,异常体系图一览,运行时异常,编译异常,try-catch方式处理异常,throws异常处理,自定义异常,throws 和 throw 的区别)

    22.1.异常介绍 Java语言中,将程序执行中发生的不正常情况称为 "异常" (开发过程中的语法错误和逻辑错误不是异常) 执行过程中所发生的异常事件分为两大类: Error:Ja ...

  7. System.ArgumentException: 已添加项。字典中的关键字:“RegEx”所添加的关键字:“RegEx” 异常的解决办法...

    详细的错误信息: 已添加项.字典中的关键字:"RegEx"所添加的关键字:"RegEx" 说明: 执行当前 Web 请求期间,出现未处理的异常.请检查堆栈跟踪信 ...

  8. 函数的定义以及关键字参数

    函数的定义以及关键字参数 4.6. 定义函数 4.7. 函数定义的更多形式 4.7.1. 参数默认值 4.7.2. 关键字参数 4.6. 定义函数 我们可以创建一个输出任意范围内 Fibonacci ...

  9. python函数定义之关键字参数

    python函数定义之关键字参数 关键字参数 关键字参数 kwarg=value 形式的 关键字参数 也可以用于调用函数.函数示例如下: def parrot(voltage, state='a st ...

  10. 什么是java的关键字_java中常见的关键字

    什么是关键字呢? 概述:关键字就是在java语言中赋予特殊含义的单词 特点:1.组成的关键字的单词全是小写 2.常见的代码编辑器中,对关键字都有特殊的颜色标记 比如在idea中对关键字都有特殊的颜色标 ...

最新文章

  1. Nature:微生物培养技术发展迅猛,未来要搞定一切!
  2. 添加css的方式:link与@import区别
  3. 常用的认证机制之session认证和token认证
  4. python进程多任务
  5. HDU1269 迷宫城堡(模板题)
  6. Log4j的使用说明
  7. JAVA进阶教学之(泛型)
  8. Python_XPath
  9. 嵌入式电路设计(符号库和封装库)
  10. C++ preprocessor /lib/cpp fails sanity check See `config.log' for more details
  11. cadence allegro - 焊盘命名规则 -unfinished -unfinished-unfinished
  12. APP自动化测试--IOS
  13. 光电信息科学与工程学c语言吗,光电信息科学与工程是热门吗?本文讲给你讲个透彻...
  14. Linux capability初探
  15. Golang学习——error错误处理浅谈
  16. 成都盛铭轩:提升店铺排名小方法
  17. linux安装包PGP加密验证
  18. html地址欄小圖標,网站地址栏前面的小图标favicon.ico制作方法
  19. 时下流行的css3页面纵向滑动效果
  20. Layui layer弹层组件 子iframe大小比父iframe大,还可对父iframe进行操作

热门文章

  1. Github精选:本周10大热门项目
  2. 对指定网站渗透的一些总结
  3. Android——ECG心电图的绘制实现
  4. MAC电脑突然开不了机的解决方案
  5. 【Github资源大汇总】 - 王朋
  6. 如何解决“App开发者需要更新此App以在此iOS版本上正常工作”
  7. 茶道形式、用具及要素
  8. nmn作用是什么意思,nmn是怎么做到抗衰老的,详细说明
  9. 服务器上网站被劫持,网站被劫持怎么办,网页被劫持快速解决办法
  10. calloc、realloc、malloc