復習 - エラー処理
CoddyのC#ジャーニー「ロジックとフロー」セクションの一部。レッスン 30/66。
チャレンジ
中級processUserDataという名前のメソッドを作成してください。このメソッドは次の処理を行います:
- 2つのパラメーターを受け取ります:string
filePathとintuserAge - usingステートメントを使用して、
filePathにあるfileの最初の行を読み取ります userAgeが18から120の間(両端を含む)であることを確認します- Ageが無効な場合、"Age must be between 18 and 120"というmessageを持つ、
InvalidUserAgeExceptionという名前のcustom exceptionをthrowします - fileが存在しない場合は、FileNotFoundExceptionをcatchして"User file not found"と出力します
- 別のIO exceptionがoccurredした場合は、それをcatchして"Error reading user data: [exception message]"と出力します
- その他のexceptionについては、"An unexpected error occurred"と出力します
- 成功した場合はfileのcontentをreturnし、いずれかのexceptionがoccurredした場合は"No data"をreturnします
自分で試してみよう
using System;
using System.IO;
class ProcessUserData
{
// ここにカスタム例外を作成してください
public static string processUserData(string filePath, int userAge)
{
// ここにコードを書いてください
}
}ロジックとフローのすべてのレッスン
自分で練習してみよう: C#オンラインコンパイラ