![](/img/trans.png)
[英]Using a try-catch exception, within the catch brackets how do I restart the program if an exception occurs?
[英]Try Catch Exception Program
您好,我在 C# 程序中遇到问题。 问题是:
“编写一个方法
ReadNumber(int start, int end)
从范围[start...end]
的控制台中读取 integer 。如果输入 integer 无效或不在所需范围内,则抛出相应的异常.
使用这种方法,编写一个程序,它采用10
整数a1, a2, ..., a10
使得1 < a1 <... < a10 < 100
。”
我到目前为止的代码:
public class NumberRange
{
public void ReadNumber(int start, int end)
{
try
{
int [] arr = new int [10];
int j = 1;
for(int i = 0; i < 10; i++, j++)
{
Console.Write("Enter Integer No " + j + ":- ");
arr[i] = Int32.Parse(Console.ReadLine());
}
Console.WriteLine("Array Values Are:- ");
for(int k = 0;k < 10; k++)
{
Console.WriteLine(arr[k]);
if (start < arr[k] && arr[k] < end)
{
Console.WriteLine("These Values Are In The Range!");
}
}
}
catch(ArgumentOutOfRangeException)
{
throw new ArgumentOutOfRangeException(
"These Values Are Not Valid Or In The Range Between 1-100!");
}
}
class Program
{
static void Main(string[] args)
{
NumberRange range = new NumberRange();
range.ReadNumber(1,100);
Console.ReadKey();
}
}
当我运行这个程序时,它不会捕获ArgumentOutOfRangeException
异常。
我尝试了很多次,但程序没有给出我期望的正确 output。
所以你需要在适当的时候抛出异常:
if (start < arr[k] && arr[k] < end)
{
Console.WriteLine("These Values Are In The Range!");
}
else
{
throw new ArgumentOutOfRangeException("These Values Are Not Valid Or In The Range Between 1-100!");
}
捕获一个异常然后抛出一个类似的异常似乎更直观,只会使代码难以阅读。
确实,测试 int 的最快方法是尝试解析,但您不想处理它抛出的所有那些混乱的异常。 为什么不使用 TryParse()?
string input; //set outside of this codes scope
bool isInteger;
int output;
isInteger = Int.TryPrase(input, out output);
if(isInteger){
//Do stuff with the integer
//Like range checks, adding to collection, etc.
}
else{
//Throw an exception
}
在那里, ReadNumber
中没有需要写入的 try/case。 所有的 Try/case 都在TryParse
内部或ReadNumber
外部。
他们可能不希望您使用这种方式来测试 int (而是自己编写基本检查代码)。 但在这种情况下,这段代码很容易适应。
脚注
如果您对如何正确处理 Parse 异常感兴趣,我曾经写过一个基本的 TryParse() 模仿:
//Parse throws ArgumentNull, Format and Overflow Exceptions.
//And they only have Exception as base class in common, but identical handling code (output = 0 and return false).
bool TryParse(string input, out int output){
try{
output = int.Parse(input);
}
catch (Exception ex){
if(ex is ArgumentNullException ||
ex is FormatException ||
ex is OverflowException){
//these are the exceptions I am looking for. I will do my thing.
output = 0;
return false;
}
else{
//Not the exceptions I expect. Best to just let them go on their way.
throw;
}
}
//I am pretty sure the Exception replaces the return value in exception case.
//So this one will only be returned without any Exceptions, expected or unexpected
return true;
}
为什么要捕获ArgumentOutOfRangeException
? 如果我们查看文档,我们会看到如果输入不是有效数字,它会抛出FormatException
。
另请注意,有两种情况会引发异常:
因此,我们可以捕获该FormatException
,然后使用自定义消息抛出我们自己的异常。 然后我们只需要检查转换后的值是否在指定范围内,如果不在,则使用自定义消息抛出不同的异常:
public static int ReadNumber(int start, int end)
{
// Make sure they entered a valid range, otherwise our comparison logic will fail later
if (end < start)
{
throw new ArgumentOutOfRangeException("'end' cannot be less than 'start'");
}
// Get user input and create a variable to store the converted value
var input = Console.ReadLine();
int result;
// Try to parse the input into our result
try
{
result = int.Parse(input);
}
catch(FormatException)
{
// If we get here, it means the input was not a valid number
throw new ArgumentException($"{input} is not a valid integer.");
}
// Last thing to do is make sure the number is within range
if (result < start)
{
throw new ArgumentOutOfRangeException($"Input cannot be less than {start}.");
}
else if (result > end)
{
throw new ArgumentOutOfRangeException($"Input cannot be greater than {end}.");
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.