简体   繁体   English

C# Try/Catch 语句,我这样做对吗?

[英]C# Try/Catch statement, am i doing this right?

using System;

namespace Something
{
    class MainProgram
    {
        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Hello? am I working?")
            }
            catch
            {
                Console.WriteLine("Nah I ain't working");
            }
        }
    }
}

I'm just poking about with C#, and I wanted to try errorchecking and whatnot.我只是在研究 C#,我想尝试错误检查等等。 There's the code and the console.有代码和控制台。 Does Catch{} just not do syntax errors? Catch{} 不会出现语法错误吗?

Catch only catches runtime errors. Catch 仅捕获运行时错误。 This can be seen as you specify what it will catch and there is no type you specify in the catch that represents syntax errors.这可以看作是您指定了它将捕获的内容,并且您在 catch 中没有指定表示语法错误的类型。

If there is a syntax error, there is no program that runs the catch in the first place.如果存在语法错误,则首先没有程序运行 catch。 The syntax error is issued by the compiler before the program exists and then is run, this is because C# is a compiled language.语法错误是在程序存在然后运行之前由编译器发出的,这是因为C#是一种编译语言。 An editor or IDE can give you an early heads-up as well, but they also don't run your program to issue those errors.编辑器或 IDE 也可以为您提供早期提示,但它们也不会运行您的程序来发出这些错误。

And yes, you can use a catch without specifying the type of Exception , but that's just a shortcut for catching all errors which derive from Exception so it is a shortcut for catch (Exception e)是的,您可以在不指定Exception类型的情况下使用 catch ,但这只是捕获从Exception派生的所有错误的快捷方式,因此它是catch (Exception e)的快捷方式

In other languages, such as JavaScript, which is an interpreted language, the interpreter (as opposed to a compiler) runs JavaScript code until it finds an error.在其他语言中,例如 JavaScript,它是一种解释性语言,解释器(与编译器相对)运行 JavaScript 代码,直到发现错误。 So you can possibly have a partially run program that has syntax errors in it.所以你可能有一个部分运行的程序,其中有语法错误。


JavaScript example, just for fun: JavaScript 示例,只是为了好玩:

try { eval('func);'); } catch (e) { console.log('The error is a syntax error: ', e instanceof SyntaxError); }

This will output "The error is a syntax error: true" because it tries to run func);这将输出 "The error is a syntax error: true" 因为它试图运行func); which is syntactically malformed.这是语法错误的。 The SyntaxError was actually issued during runtime (remember, this is JavaScript not C#). SyntaxError 实际上是在运行时发出的(请记住,这是 JavaScript 而不是 C#)。

Try/Catch is not for SyntaxErrors, but Runtime errors. Try/Catch 不是针对 SyntaxErrors,而是针对运行时错误。 You can do你可以做

try{
  // Code here
} catch(Exception e){
  // log the exception
} finally{
  // code here will run no matter what (with or without errors)
}

As you can see, catch can optionally take a Exception parameter that can help you log it better.如您所见,catch 可以选择采用一个Exception参数,该参数可以帮助您更好地记录它。 In your case, you will catch all exceptions, but you don't have a reference to the exception.在您的情况下,您将捕获所有异常,但您没有对异常的引用。

Try catch is usually used for cases like reading from a file/database, making web requests, etc. All these things may fail for external reasons but they are Syntax-wise correct. Try catch 通常用于从文件/数据库读取、发出 Web 请求等情况。所有这些事情都可能由于外部原因而失败,但它们在语法上是正确的。

This has already been answered but just to give you confidence the others are correct yes.这已经得到了回答,但只是为了让您相信其他人是正确的。

You typically will try to do something for example simply call a method or do some complicated logic you want to make sure doesn't exit out so you would write:你通常会尝试做一些事情,例如简单地调用一个方法或做一些你想确保不会退出的复杂逻辑,所以你会写:

try{ XYZ } catch(Exception e){}尝试{ XYZ } 捕获(异常 e){}

if you know the kind of exception that you are going to encounter whether it be a argumentoutofrange exception or nullpointerexception or anything specific like that you can change the catch to focus on that type.如果您知道将遇到的异常类型,无论是argumentoutofrange 异常还是nullpointerexception 或任何类似的特定异常,您都可以更改catch 以专注于该类型。

The general Exception type is okay for working out issues when you don't know exactly what the problem is but I would say find out what the exception is and cater your response to best deal with it.当您不确切知道问题是什么时,一般的异常类型可以解决问题,但我会说找出异常是什么并满足您的响应以最好地处理它。

Sorry this was very wordy I just think understanding is more important since you seem new.对不起,这很罗嗦,我只是认为理解更重要,因为你看起来很新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM