java学习(18-异常)

1.异常处理

捕获:Java中对异常有针对性的语句进行捕获,可以对出现的异常进行指定方式的处理捕获异常格式:
try {
    //需要被检测的语句。
}
catch(异常类 变量) { //参数。
    //异常的处理语句。
}
finally {
    //一定会被执行的语句。
package com.daigua18;


public class ExceptionDemo {
    public static void main(String[] args) throws Exception {
        try {
            System.out.println(1 / 0);
        } catch (Exception ArithmeticException) {
            System.out.println("错误!");
        } finally {
            System.out.println(1);
        }
    }
}

2.Throwable常用方法

String getMessage()  返回此 throwable 的详细消息字符串
String toString()  返回此 throwable 的简短描述
void printStackTrace()  打印异常的堆栈的跟踪信息

代码:

package com.daigua18;
/*
 * Throwable的常用方法:
        String getMessage()
        String toString()
        void printStackTrace()
 *
 */

public class ExceptionDemo2 {
    public static void main(String[] args) throws Exception {
        try {
            System.out.println(1 / 0);
        } catch (ArithmeticException e) {
            System.out.println(e.toString());
            System.out.println("---");
            System.out.println(e.getMessage());
            System.out.println("---");
            e.printStackTrace();
        }
    }
}

3.自定义异常

package com.daigua18;


public class ExceptionDemo3 {
    public static void main(String[] args) {
        try {
            checkGrade(11);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    private static void checkGrade(int score) throws Exception {
        if (score < 0 | score > 100) {
            throw new RuntimeException("考试成绩不对!");
        }
        System.out.println("成绩为:" + score);
    }

}

4.递归

4.1阶乘

package com.daigua18;
// 递归求阶乘
public class RecursiveDemo {
    public static void main(String[] args) {
        System.out.println(JC(3));
    }

    private static int JC(int num){
        if(num <= 1){
            return 1;
        }
        else{
            return num * JC(num-1);
        }

    }

}

4.2斐波纳挈数列

package com.daigua18;
// 求斐波纳挈数列
public class FiboDemo {
    public static void main(String[] args) {
        System.out.println(FB(6));
    }

    private static int FB(int index){
        if(index == 1 | index == 2){
            return 1;
        }else {
            return FB(index-1) + FB(index-2);
        }
    }
}
原文地址:https://www.cnblogs.com/daigua/p/java-xue-xi-18yi-chang.html