相关疑难解决方法(0)

如果try-catch可以用if-then-else替换,推荐哪一个?

在我粗略的调查中,我认为任何错误都可以通过使用if-then-else构造来处理.我们举一个简单的例子如下.

除以零可以处理

int x=1;
int y=0;
if(y==0)
    Console.WriteLine("undefined");
else
    Console.WriteLine("x/y={0}",x/y);
Run Code Online (Sandbox Code Playgroud)

替换try-catch等价物

int x=1;
int y=0;
try
{
    Console.WriteLine("x/y={0}",x/y);
}
catch
{
    Console.WriteLine("undefined");
}
Run Code Online (Sandbox Code Playgroud)

如果try-catch可以用if-then-else替换,推荐哪一个?

c#

2
推荐指数
1
解决办法
1499
查看次数

为什么Scanner使用Scanner#ioException()而不是抛出异常?

这有什么好处/垮台吗?

通常,从流中读取时会抛出异常:

try {
    inputStream.read();
}catch(IOException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

但是当使用a时Scanner,你不会被迫处理异常.相反,如果抛出一个,你会使用Scanner#ioException().

我知道Scanner不是一个流,而不是一个解析数据的tokenizer,如果需要,但为什么它处理它的异常不像其他涉及IO的行为?我什么时候应该以这种方式处理异常?

java ioexception java.util.scanner

2
推荐指数
1
解决办法
2425
查看次数

如何从 try/catch 内部中断循环?

我正在为学校做一个简单的课程项目,以试验 C# 中的继承和其他要点,但我在某些部分遇到了问题。我相信我需要在无条件 while 循环中尝试捕获,以确保用户以正确的形式输入数据,但我还需要能够从错误处理代码中跳出循环。我在给我带来问题的代码下面添加了注释。

class Program : students
{
    static void Main(string[] args)
    {
        students stu = new students();

        Console.Write("Number of students are you recording results for: ");
        int studNum = int.Parse(Console.ReadLine());
        stu.setNoOfStudents(studNum);
        Console.WriteLine();

        for (int a = 0; a < studNum; a++)
        {
            Console.Write("{0}. Forename: ", a + 1);
            stu.setForname(Console.ReadLine());
            Console.Write("{0}. Surname: ", a + 1);
            stu.setSurname(Console.ReadLine());
            while (0 == 0)
            {
                try
                {
                    Console.Write("{0}. Age: ", a + 1);
                    stu.setstudentAge(int.Parse(Console.ReadLine()));
                    Console.Write("{0}. Percentage: ", a + 1);
                    stu.setpercentageMark(int.Parse(Console.ReadLine())); …
Run Code Online (Sandbox Code Playgroud)

c# try-catch break while-loop

2
推荐指数
1
解决办法
4181
查看次数

IntelliJ IDEA 检查警告参数可能为 null

有没有办法告诉IDEA以下内容可以:

public static void main(String[] args) {
    String stringValue = args.length > 0 ? args[0] : null;
    long longValue;
    try {
        longValue = Long.parseLong(stringValue);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("hmm...", e);
    }
    System.out.println(longValue);
}
Run Code Online (Sandbox Code Playgroud)

它坚持突出显示stringValue并警告“Argument stringValue might be null”。我知道可能会,但如果是的话,异常就会被捕获。

java intellij-idea

2
推荐指数
1
解决办法
2001
查看次数

以相同的方法抛出并捕获异常

在我写入数据库的方法中,我处理错误,如下面的代码所示.在catch (DbUpdateException ex)我想重新抛出异常并在最后捕获它catch (Exception ex).

这可能吗,怎么做?下面的代码不会这样做.

        using (Entities context = new Entities())
        {
            try
            {
                context.Office.Add(office);
                retVal = context.SaveChanges();
            }
            catch (DbUpdateException ex)
            {
                SqlException innerException = ex.GetBaseException() as SqlException;
                if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
                {
                    throw
                        new Exception("Error ocurred");
                }
                //This is momenty where exception is thrown.
                else
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                throw
                    new Exception("Error");
            }
        }
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-mvc entity-framework

1
推荐指数
1
解决办法
1986
查看次数

使用try {...} catch(..){...}代替转到

是不好的做法使用像goto一样的试试?例如,简单的代码

try{
    if(argc<2){
        std::cout<<"no inputfile"<<std::endl;
        throw 1;
    }
    STARTUPINFO cif;
    ZeroMemory(&cif,sizeof(STARTUPINFO));
    PROCESS_INFORMATION pi;
    if(FALSE==CreateProcess(argv[1],NULL,NULL,NULL,FALSE,NULL,NULL,NULL,
                            &cif,&pi)){
        printf("smth is wrong");
        throw 1;
    }
    WaitForSingleObject(pi.hProcess, INFINITE);
    GetExitCodeProcess(pi.hProcess, &exitCode);
    std::cout<<"Process return"<<exitCode<<std::endl;
    throw 1;
}
catch(int a){
    printf("press Enter");
    getchar();
}
Run Code Online (Sandbox Code Playgroud)

c++ goto try-catch

1
推荐指数
1
解决办法
1006
查看次数

Java:在二维数组中搜索单词

我已经学习Java大约4个月了,这是我学习的第一门编程语言.对于学校,我们必须做一个项目,一个基于控制台的游戏.我选择了Boggle.

我有一个带有骰子的ArrayList,每个都有一个随机的"向上",然后ArrayList被洗牌,一个二维数组充满了每一面的值.此时阵列充满了字符串,字符可能是更好的选择,但是很容易改变.

我面临的问题是我需要能够在数组中找到单词.Boggle中的单词可以向任何方向移动,每个单独的块只能使用一次,但路径可以交叉,也可以对角搜索.我设法找到数组中是否存在第一个字母.如果不是,则可以中止搜索,如果存在,则需要开始搜索,搜索单词的第二个字符,该字符必须在第一个字符的块周围.

我做了一些数学运算,发现它总是以"i-1和j-1"为例,作为周围区块的左上角.我解决了这个问题,但似乎无法找到单词...而且,如果周围有2个"e",我不知道如何搜索每个"e"的单词.到目前为止,这是我的代码:

这是我目前最重要的课程,Gameboard类

public class Gameboard {

private List<Dice> dices = new ArrayList<Dice>();
private final int boardSize;
private String[][] board;
private boolean [][] blocksAvailable;
private Random random = new Random();

public GameBoard() {
    // Making the board with a given size (will be changeable later but is "4" for now)
    boardSize = 4;
    board = new String[boardSize][boardSize];
    blocksAvailable = new boolean[boardSize][boardSize];
    for(int i = 0; i < boardSize; i++) {
        for(int j = 0; j < boardSize; j++) …
Run Code Online (Sandbox Code Playgroud)

java search multidimensional-array

1
推荐指数
1
解决办法
3407
查看次数

我应该使用Try Catch Block来实现我的业务逻辑吗?

假设我需要这样的东西.(这段代码很错误,但只是一个例子).这段代码不是我的问题!这只是一个例子.我知道如何使用if else语句编写它.我正在考虑一个更复杂的背景!

int[] arraynums = new int[3] {1,2,3};
int Sample = 0;
try
{
Sample = arraynums[3];
}
catch
{
Sample=4;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我可以使用一个不会遇到错误的替代逻辑.但是如果我使用try catch块,我仍然可以减少代码.是否建议使用try catch块来解决逻辑?如果不是,为什么呢?

c# c++ java

0
推荐指数
1
解决办法
1019
查看次数

处理system.Format Exception C#

在我的应用程序中,我不明白如何处理system.format异常.见下面的代码

public Harvest_Project(XmlNode node)
    {
        this._node = node;
        this._name = node.SelectSingleNode("name").InnerText;

        this._created_at = storeTime(node.SelectSingleNode("created-at").InnerText);
        this._updated_at = storeTime(node.SelectSingleNode("updated-at").InnerText);
        this._over_budget_notified_at = storeTime(node.SelectSingleNode("over-budget-notified-at").InnerText);
        this._latest_record_at = storeTime(node.SelectSingleNode("hint-latest-record-at").InnerText);
        this._earliest_record_at = storeTime(node.SelectSingleNode("hint-earliest-record-at").InnerText);

        this._billable = bool.Parse(node.SelectSingleNode("billable").InnerText);

        try
        {
                this._id = Convert.ToInt32(node.SelectSingleNode("id").InnerText);
                this._client_id = Convert.ToInt32(node.SelectSingleNode("client-id").InnerText);
                this._budget = float.Parse(node.SelectSingleNode("budget").InnerText);
                this._fees = Convert.ToInt32(getXmlNode("fees", node));

        }
        catch (FormatException e)
        {

           Console.WriteLine();
        }
        catch (OverflowException e)
        {
            Console.WriteLine("The number cannot fit in an Int32.");
        }

        this._code = node.SelectSingleNode("code").InnerText;
        this._notes = node.SelectSingleNode("notes").InnerText;

    }
Run Code Online (Sandbox Code Playgroud)

在这里,尝试并捕获块,所有节点都采用int值,但是,因为_fees取"0"值.它显示了格式异常.我只是希望我的节点不显示空字符串.我想处理这个异常.这意味着,它不应该在"this._fees = Convert.ToInt32(getXmlNode("fees",node))"行中抛出异常;" 因为它返回了我想要的int值.

我怎么能实现这一目标?

c# wpf exception-handling formatexception

0
推荐指数
1
解决办法
1069
查看次数

Java - 素数算法实现不起作用

我写了这段代码,它应该搜索素数并将它们放入数组中.这里是:

int[] prime_array = new int[(int)s.upper_bound];
int index_in_array = 0;
boolean are_we_done = false;
int index = 1;
boolean is_prime = true;

while (!are_we_done) {
    try {
        for (int i = 1; i < index; i++) {
            if ((index%i)==0) {
                is_prime = false;
            }
        }

        if (is_prime) {
            prime_array[index_in_array] = index;
            index_in_array++;
        }

        index++;
        is_prime = true;
    } 
    catch (IndexOutOfBoundsException e) {
        are_we_done = true;
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它捕获的唯一主要是1.任何想法为什么它不起作用?

java primes

0
推荐指数
1
解决办法
86
查看次数

如何在没有 if else 语句的情况下验证这些变量?

我对 C# 很陌生,所以请原谅我缺乏知识。我只是想检查以下内容:

  • “卡号长度”= 16
  • “卡 PIN 码长度”= 3
  • "CardNameHasSpace" 0 我不想使用 if else 语句,还有其他方法吗?

代码:

public bool Validate()
{
    CardNumberLength = Convert.ToString(GetCardNumber()).Length;

    CardPINLength = Convert.ToString(GetCardPIN()).Length;

    CardNameHasSpace = GetCardName().IndexOf(" ");
}
Run Code Online (Sandbox Code Playgroud)

c#

0
推荐指数
1
解决办法
212
查看次数