一、实验目的
- 理解Java的异常处理机制。
- 掌握常用的异常处理方法,能够熟练使用try…catch和throw处理异常。
- 了解常用的内置异常类。
- 掌握自定义异常的编写与使用方法
二、实验内容、过程及结果
*12.3 (ArrayIndexOutOfBoundsException) Write a program that meets the following requirements:
■ Creates an array with 100 randomly chosen integers.
■ Prompts the user to enter the index of the array, then displays the corresponding element value. If the specified index is out of bounds, display the
message Out of Bounds.
*12.3 (ArrayIndexOutOfBoundsException)编写满足如下要求的程序
创建一个包含100个随机选择的整数的数组。
■提示用户输入数组的索引,然后显示对应的元素值。如果指定的索引越界,则显示
消息越界。
运行代码如下 :
package chapter12;
import java.util.Scanner;
public class Code_03 {public static void main(String[] args) {int[] number = new int[100];for (int i = 0;i < 100;i++)number[i] = (int)(Math.random());System.out.print("Enter the index of array: ");Scanner input = new Scanner(System.in);int index = input.nextInt();try {System.out.println("The number of index" + index + " is " + number[index]);}catch (ArrayIndexOutOfBoundsException ae){System.out.println("Out of bound");}}
}
运行结果
*12.5 (IllegalTriangleException) Programming Exercise 11.1 defined the
Triangle class with three sides. In a triangle, the sum of any two sides is
greater than the other side. The Triangle class must adhere to this rule.
Create the IllegalTriangleException class, and modify the constructor
of the Triangle class to throw an IllegalTriangleException object if a
triangle is created with sides that violate the rule, as follows:
/** Construct a triangle with the specified sides */
public Triangle(double side1, double side2, double side3)
throws IllegalTriangleException {
// Impleme
*12.5 (IllegalTriangleException)
有三条边的三角形类。在三角形中,任意两条边的和是比另一边更大。
Triangle类必须遵守这条规则。
创建IllegalTriangleException类,并修改构造函数
抛出一个IllegalTriangleException对象
三角形的边违反规则,如下所示:
/**用指定的边构造一个三角形*/
公共三角形(双面1,双面2,双面3)
抛出IllegalTriangleException
/ / Impleme
运行代码如下 :
import java.util.Scanner;
public class Unite12Test5
{public static void main(String[] args) {try {Triangle t = new Triangle(1,2,1);} catch (IllegalTriangleException e) {System.out.println(e);}}
}
class Triangle extends SimpleGeometricObject
{double side1=1.0;double side2=1.0;double side3=1.0;public Triangle() {}public double getSide1() {return side1;}public void setSide1(double side1) {this.side1 = side1;}public double getSide2() {return side2;}public void setSide2(double side2) {this.side2 = side2;}public double getSide3() {return side3;}public void setSide3(double side3) {this.side3 = side3;}public Triangle(double side1,double side2,double side3)throws IllegalTriangleException{this.side1=side1;this.side2=side2;this.side3=side3;if(side1+side2<=side3||side1+side3<=side2||side3+side2<=side1) {throw new IllegalTriangleException("该三角形错误");}}public double getArea() {double s = (this.side1+this.side2+this.side3)/2;return Math.sqrt(s*(s-this.side1)*(s-this.side2)*(s-this.side3));}public double getPerimrter() {return this.side1+this.side2+this.side3;}public String toString() {return "Triangel: side1:"+side1+" side2 = "+side2+" side3 = "+side3;}
}
class IllegalTriangleException extends Exception
{String message ;public IllegalTriangleException() {message = "该三角形错误";}public IllegalTriangleException(String argu){message = argu;}@Overridepublic String toString(){return message;}}
运行结果
*12.6 (NumberFormatException) Listing 6.8 implements the hex2Dec(String
hexString) method, which converts a hex string into a decimal number.
Implement the hex2Dec method to throw a NumberFormatException if the
string is not a hex string.
*12.6 清单6.8实现了hex2Dec(String . exceptionhexString)方法,将十六进制字符串转换为十进制数字。
实现hex2Dec方法以抛出NumberFormatException
String不是十六进制字符串。
运行代码如下 :
package Recursive;import java.util.Scanner;public class Exercise18_24 {public static void main(String[] args) {System.out.print("Enter a hex string: ");StringBuilder hexString = new StringBuilder(new Scanner(System.in).nextLine());System.out.println("The decimal of hex string " + hexString + " is " + hex2Dec(hexString.reverse().toString()));}/** 返回十六进制的十进制表示 */public static int hex2Dec(String hexString) {String hex = "0123456789ABCDEF";int decimal = hex.indexOf(Character.toUpperCase(hexString.charAt(hexString.length() - 1)));decimal *= (int)Math.pow(16, hexString.length()-1);return (hexString.length() == 1) ? decimal :decimal + hex2Dec(hexString.substring(0, hexString.length()-1));}
}
运行结果
*12.8 (HexFormatException) Exercise 12.6 implements the hex2Dec method to
throw a NumberFormatException if the string is not a hex string. Define
a custom exception called HexFormatException. Implement the hex2Dec
method to throw a HexFormatException if the string is not a hex string.
*12.8 (HexFormatException)练习12.6实现了hex2Dec方法
如果字符串不是十六进制字符串,则抛出NumberFormatException。
定义一个名为HexFormatException的自定义异常。
实现hex2Dec
方法在字符串不是十六进制字符串时抛出HexFormatException。
运行代码如下 :
package pack1;public class HexFormatException extends Exception{public HexFormatException() {}public HexFormatException(String message) {super(message);}@Overridepublic String getMessage() {return super.getMessage();}
}
package pack1;import java.util.Scanner;public class TestHexFormatException {public static void main(String[] args) throws HexFormatException {try(Scanner input = new Scanner(System.in);) {try {System.out.print("Enter a hex string: ");System.out.println("The decimal of hex string that you enter is " + hecToDec(input.next()));}catch (HexFormatException e) {System.out.println(e.getMessage());}}}/**十六进制转换为十进制*/public static int hecToDec(String hexString) throws HexFormatException {try {int integer = Integer.parseInt(hexString);if (integer < 0 || integer > 9) //数字错误时,抛出异常throw new HexFormatException("Error hex string");return integer;} catch (java.lang.NumberFormatException e) {switch (hexString) {case "A":return 10;case "B":return 11;case "C":return 12;case "D":return 13;case "E":return 14;case "F":return 15; //非指定字符时抛出异常default:throw new HexFormatException("Error hex string");}}}
}
运行结果
三、实验结论
通过本次实验实践遇到错误、不怕错误、改正错误的知识和操作,磨砺了意志,得到了学习不可能一帆风顺,遭遇挫折也未必是坏事,感悟在学中学,问中学,改中学。
结语
不要追求速成
比成功更有价值的是你为之努力的过程
!!!