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。程序报错,不再继续运行。