I have a program in C# that works fine when I run it in Visual Studio.
But when I run the file I get an error in main.
The error is:
Unhandled Exception: System.IndexOutOfRangeException: Index was out of bounds of the array
My main: The error Is at int tala = convert.toInt32...
namespace MultiplicationTable
{
class Program
{
static void Main(string[] args)
{
int tala = Convert.ToInt32(args[0]);
MultiplicationTable test = new MultiplicationTable(tala);
Console.ReadLine();
}
}
}
Any ideas?
Problem : When you run it from Visual Studio you are providing the arguments but when you run the program directly by double clicking on it you can not provide the arguments as it willbe invoked directly.
Solution : you need to provide command line arguments properly, follow the below steps to run your program from command line
Step 1: goto Command Prompt
Step 2: goto your program exe file path
Step 3: now execute the program by providing commandline arguments as below:
c:\myprogrampath\program.exe 12
Try This code to avoid Exceptions:
if(args.Length>0)
{
int tala = Convert.ToInt32(args[0]);
MultiplicationTable test = new MultiplicationTable(tala);
Console.ReadLine();
}
else
{
Console.WriteLine("No Command Line Arguments - Quiting");
}
Yes,
as the poster before said, either you have to pass arguments to your program or you have to check, if args is not null with an if-statement and "catch" this error.
if(args) {
//here your code
}
Alternatively, you could try an try - catch statement:
try {
//here you read the arguments and pass to a variable
}
catch(System.IndexOutOfRangeException) {
//other codepart
}
来源:https://stackoverflow.com/questions/21783392/system-indexoutofrangeexception-index-was-out-of-bounds