How to do exception handling in my code

2019-08-30 04:11发布

I just learned about exception handling. So, I am still getting use to it. I know how to do the basic exception handling like entering in a correct value for division and having it throw a DividebyZeroException if a incorrect value is entered.

But I need help some help on doing the following:

Create an exception handling to throw an error if

1) The number of integer in each row are not equal to each other for example: Matrix = [ 3 4; 9 8 1] should be: matrix = [ 3 4 2; 9 8 1]

2) the semicolon ";" that I use as a separator is replace by an invalid character such as: matrix = [ 3 4 2 # 9 8 1]

This is my code:

this is from my main in which I create the string.

string text = "A = [8 5 5 4; 2 6 5 3; 8 5 2 6]";

this is my class

public string[,] Matrix(string text)
{
    try
    {
        char[] splitOne = { '[', ']' };
        char[] splitTwo = { ';' };
        char[] splitThree = { ' ' };
        words = text.Split(splitOne)[1]
                               .Split(splitTwo, StringSplitOptions.RemoveEmptyEntries)
                               .Select(x => x.Split(splitThree, StringSplitOptions.RemoveEmptyEntries))
                               .ToArray();
    }
    catch
    {
        Console.WriteLine("Try entering a correct string");

    }


    string[,] matrix = new string[words.Length, words[0].Length];
    for (int i = 0; i < words.Length; ++i)
    {
        for (int j = 0; j < words[i].Length; ++j)
        {
            matrix[i, j] = words[i][j];
        }
    }

    for (int i = 0; i < matrix.GetLength(0); i++)
    {
        for (int j = 0; j < matrix.GetLength(1); j++)
        {
            Console.Write("{0} ", matrix[i, j]);
        }
        Console.WriteLine();
    }
    return matrix;
}

How would I make the try and catch work? This is a basic general catch all but how would I make it work with my following requirements as well. Right now it is not outputting my message.

1条回答
何必那么认真
2楼-- · 2019-08-30 04:25

You misunderstanding Exceptions, you want to use Exceptions as rules for your data structure. Instead Exceptions is when an error occour in a method, as you are dividing with 0 in a math operation. This is a critical error, where the code does not know what to do.

For this concrete example, you should do if statements. Because you want to apply rules and enforce it and Exceptions does not fit these use cases well, if you where to implement it, you would need if statements to check if the string you want to apply the rules to, was well formed after your standards and after that throw an Exception. Moreso this makes sense if you are creating a library.

My solution to what the code should look like.

String text = "A = [8 5 3 4; 2 6 5 3; 8 5 2 3]";

var startIndex = text.IndexOf('[') + 1;
var length = text.IndexOf(']') - startIndex;
text = text.Substring(startIndex, length);

if(!text.Contains(";"))
{
    Console.WriteLine("malformed seperator");

    return;
}

var test = text.Split(';').Select((k, i) => new {Key = i, Value = k.Replace(" ", "").Length});


if(!test.All(x => x.Value == test.First().Value))
{
    Console.WriteLine("unbalanced array");
    return;
}

But i think you are making your self work harder then you should, your design implies that a lot of things goes right in the string creation and using already build matrix libraries would save a lot of work here.

EDIT

Updated the solution to work, but i still think the design of the string matrix forces the code in a lot of directions that is unecesary.

查看更多
登录 后发表回答