Java try catch throw exception 和 finally用法举例详解

Catch exception用来检测exception,当try里的代码出现exception,运行直接转入catch,try里的代码不再运行。

finally里的代码在运行完catch后无论怎样都一定会运行。

Catch example:

import javax.swing.*;

public class DateReader {
	public static int getYear(String d) {
		String yearString = d.substring(6, 10);  
		System.out.println("Done with substring method...");
		return Integer.parseInt(yearString);    
	}
	
	public static void main(String[] args) {
		String d = "";
		try {
			d = JOptionPane.showInputDialog("Enter date: (mm/dd/yyyy)");
			int year = getYear(d);
			System.out.println("The year is " + year);
		} catch(IndexOutOfBoundsException e) {
			System.out.println("index error");
		} catch(NumberFormatException e) {
			System.out.println("Number format problem");
			return;  
		} finally{
			System.out.println("Original string was: " + d);
		}
		System.out.println("At bottom of main method...");
	}

}
输入为:

12/25/2017

输出为:

Done with substring method...
The year is 2017
Original string was: 12/25/2017
At bottom of main method...
输入为:

abcdefghijk

输出为:

Done with substring method...
Number format problem
Original string was: abcdefghijk
输入为:

9

输出为:

index error
Original string was: 9
At bottom of main method...


Throw expection 是用来弹出错误信息(报错)的,(不跳过)

Throw example:

import java.util.Random;
import java.util.Scanner;

public class RandomTriangleMaker {

	private static Random randomGenerator = new Random();
	
	private static int getRandomLength() {
		return randomGenerator.nextInt(10) + 1;
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("How many triangles would you like? ");
		int trianglesNeeded = sc.nextInt();
		while (trianglesNeeded > 0) {
			int s1 = getRandomLength();
			int s2 = getRandomLength();
			int s3 = getRandomLength();
			double area;
			area = TriangleAreaCalculator.findArea(s1, s2, s3);
			System.out.print(s1 + ", " + s2 + ", " + s3);
			System.out.println(": area = " + area);
			trianglesNeeded--;
		}
	}

}

public class TriangleAreaCalculator {

	/* Calculate area of triangle given lengths of three sides.
	 * This formula is attributed to a guy named "Heron", but 
	 * was actually known to Archimedes!     
	 */
	public static double findArea(double s1, double s2, double s3) {
		double u = (s1 + s2 + s3) / 2;
		double v = u * (u - s1) * (u - s2) * (u - s3);
		
		if (v <= 0) {
			throw new ArithmeticException("Illegal side values: " + 
		       s1 + ", " + s2 + ", " + s3);
		}
		
		return Math.sqrt(v);
	}
	
	
}
此程序是一个随机生成三角形并进行面积计算的程序。在计算面积的过程中,若随机生成的三角形两边之和不大于第三边,则这个三角形无法生成,会throw exception。程序报错,不再继续运行。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值