始める無料で始める

Try-catch

ゼロ除算による算術例外を捕捉し、メッセージを表示して処理します。あらかじめ読み込まれている BigDecimal パッケージの使いどころも、あわせて確認できます。

この演習はコースの一部です

Javaにおけるデータ型と例外処理

コースを見る

演習の手順

  • try を追加し、try のコードブロックを開始します。
  • (ArithmeticException e)ArithmeticException を捕捉し、catch のコードブロックを開始します。
  • catch のコードブロックを終了します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

class SplitTheBill {
	public static void main(String[] args) {
		BigDecimal bill = new BigDecimal(125.50);
		computeEachBill(bill, 5);
		computeEachBill(bill, 0);
	}

	public static void computeEachBill(BigDecimal bill, int people) {
		// Add a try and the beginning of the try code block
		____ ____
			BigDecimal numPeople = new BigDecimal(people);
			BigDecimal individualBill = bill.divide(numPeople);
			System.out.println("Bill for each person is: " + individualBill);
			// End the try code block and catch a possible ArithmeticException
        ____ ____ (ArithmeticException e) ____
			System.out.println("You didn't provide a positive number of people to split the bill among.");
			// End the catch code block
		____
	}
}
コードを編集して実行