try… catch… when…

date
Aug 3, 2022
slug
10038
status
Published
tags
C#
summary
type
Post
using System.Text;
using static System.Console;
using static System.Convert;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Before parsing");
            Write("What is your age? ");
            string? input = ReadLine(); // or use "49" in a notebook
            try
            {
                int age = int.Parse(input);
                WriteLine($"You are {age} years old.");
            }
            catch (FormatException)
            {
                Console.WriteLine("The age you entered is not a valid number format.");
            }
            catch (Exception ex)
            {
                WriteLine($"{ex.GetType()} says {ex.Message}");
            }
            WriteLine("After parsing");
        }
    }
}
如果没有第一个catch,input输入为字母,错误就会被catch捕捉,输出:
Before parsing
What is your age? Kermit
System.FormatException says Input string was not in a correct format.
After parsing
这时候知道了错误的类型为FormatException,就可以直接捕捉这个类型,所以加入第一catch,输入字母错误变为:
Before parsing
What is your age? Kermit
The age you entered is not a valid number format.
After parsing
但是第二个catch要保留,应为还有其他类型的exception,可以查看parse的exception:
// Exceptions:
//   T:System.ArgumentNullException:
//     s is null.
//
//   T:System.FormatException:
//     s is not in the correct format.
//
//   T:System.OverflowException:
//     s represents a number less than System.Int32.MinValue or greater than System.Int32.MaxValue.
还可以用when的方式加条件:
Write("Enter an amount: ");
string? amount = ReadLine();
try
{
decimal amountValue = decimal.Parse(amount);
}
catch (FormatException) when (amount.Contains("$"))
{
WriteLine("Amounts cannot use the dollar sign!");
}
catch (FormatException)
{
WriteLine("Amounts must only contain digits!");
}

© Wen Bo 2021 - 2025