Java异常的知识讲解

x33g5p2x  于2021-11-22 转载在 Java  
字(1.4k)|赞(0)|评价(0)|浏览(472)

创建一个 Java 数组,然后访问不存在的数组数据,看看会抛出什么异常:

我们可以看到抛出了一个ArrayIndexOutOfBoundsException:异常:数组下标越界

执行代码 System.out.println(1 / 0),看看会抛出什么异常。

现在抛出了一个ArithmeticException: / by zero异常

  1. Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.
  2. 当出现异常的运算条件时,抛出此异常。
  3. 例如,一个整数“除以零”时,抛出此类的一个实例。

自定义异常:

  1. package 任务5;
  2. /** * @author ${范涛之} * @Description * @create 2021-11-18 0:10 */
  3. public class MyExpection {
  4. public static void main(String[] args) throws GenderException {
  5. Human human = new Human();
  6. human.setGender("牛");
  7. }
  8. public static class Human{
  9. static String gender;
  10. public static void setGender(String s) throws GenderException{ //这里抛出了自己的异常
  11. GenderException g= new GenderException();
  12. if (!s.equals("男") && !s.equals("女")){
  13. // throw new GenderException("");
  14. // throw new GenderException("你输入了错误的性别");
  15. // throw new GenderException(g,"你输入了错误的性别");
  16. throw new GenderException("你输入了错误的性别");
  17. }
  18. else {
  19. gender = s;
  20. }
  21. }
  22. }
  23. public static class GenderException extends Exception{
  24. /** * 构造方法1:无异常 */
  25. public GenderException(){
  26. super();
  27. }
  28. /** * 构造方法二:有字符串异常 * @param message */
  29. public GenderException(String message){
  30. super(message);
  31. }
  32. /** * 构造方法三:有字符串和Throwable类型参数,表明异常可以抛出 * @param message * @param cause */
  33. public GenderException(Throwable cause,String message){
  34. super(message,cause);
  35. }
  36. /** * 构造方法四:有Throwable类型参数,表明异常可以抛出 * @param cause */
  37. public GenderException(Throwable cause){
  38. super(cause);
  39. }
  40. }
  41. }

不同的输出结果:

相关文章