Try/Catch + Using, Right Syntax

try/catch + using, right syntax

I prefer the second one. May as well trap errors relating to the creation of the object as well.

Where do I put try/catch with using statement?

If your catch statement needs to access the variable declared in a using statement, then inside is your only option.

If your catch statement needs the object referenced in the using before it is disposed, then inside is your only option.

If your catch statement takes an action of unknown duration, like displaying a message to the user, and you would like to dispose of your resources before that happens, then outside is your best option.

Whenever I have a scenerio similar to this, the try-catch block is usually in a different method further up the call stack from the using. It is not typical for a method to know how to handle exceptions that occur within it like this.

So my general recomendation is outside—way outside.

private void saveButton_Click(object sender, EventArgs args)
{
try
{
SaveFile(myFile); // The using statement will appear somewhere in here.
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
}

Try catch throw won't work for a wrong string

Try-Catch Blocks

Try-catch blocks are made so that your program doesn't suddenly crash in case of a run-time error. They are not for catching syntax error. But they can only catch errors that occur while runtime.

You cannot use try-catch blocks to handle syntax errors as they are thrown while the code is being parsed and not while it's running.

You can catch programmer-generated and runtime exceptions with try-catch block of error handling, but you cannot catch JavaScript syntax errors.


Now you may be wondering, if Javascript can't catch syntax errors, then why is the SyntaxError an error type that can be caught in try-catch block?

  • In Javascript, SyntaxError are errors that will be thrown during runtime, not during compile-time.

  • For eg. JSON.parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

try catch mechanism in c++

C++ has a diverse range of error handling for different problems.

Division by zero and many other errors (null pointer access, integer overflow, array-out-of-bounds) do not cause an exception that you can catch.

You could use tools such as clang's undefined behavior sanitizer to detect some of them, but that requires some extra work on your part, and comes with a performance hit.

The best way in C++ to deal with prevention of a division by zero, is to check for it:

    int res;
int a=1;
int b=0;

if (b == 0)
{
int stop=1;
}
else
{
res = a/b;
}

See also the answers to this other very similar question.

Try/catch syntax

MySQL doesn't have TRY/CATCH functionality. You can use handlers.

Using statement with try catch. What happens to instance from using statement?

You can think of using as a short-hand for try-finally. Hence your code is equivalent to:

IDatabaseConnectivityObject databaseConnectivityObject = new DbProviderFactoryConnectionBasicResponse();
try
{
try
{
Foo();
}
catch(ArgumentNullException e)
{
throw;
}
}
finally
{
if(databaseConnectivityObject != null)//this test is often optimised away
databaseConnectivityObject.Dispose()
}

Looked at this way, you can see that the Dispose() will indeed be called if the exception throws, because the try-finally is outside of the try-catch.

This is precisely why we use using.

Syntax error in Try & Catch

In addition to Jens' answer, you can use lambda in Java 8, because EventHandler is a functional interface. Then your code will look like:

txt.setOnAction(event -> {
try {
engine.load(txt.getText());
}catch (Exception e) {
showError("Unable to load site");
}
});

Correct Try...Catch Syntax Using Async/Await

It seems to be best practice not to place multiple lines of business logic in the try body

Actually I'd say it is. You usually want to catch all exceptions from working with the value:

try {
const createdUser = await this.User.create(userInfo);

console.log(createdUser)
// business logic goes here
} catch (error) {
console.error(error) // from creation or business logic
}

If you want to catch and handle errors only from the promise, you have three choices:

  • Declare the variable outside, and branch depending on whether there was an exception or not. That can take various forms, like

    • assign a default value to the variable in the catch block
    • return early or re-throw an exception from the catch block
    • set a flag whether the catch block caught an exception, and test for it in an if condition
    • test for the value of the variable to have been assigned
      let createdUser; // or use `var` inside the block
    try {
    createdUser = await this.User.create(userInfo);
    } catch (error) {
    console.error(error) // from creation
    }
    if (createdUser) { // user was successfully created
    console.log(createdUser)
    // business logic goes here
    }
  • Test the caught exception for its type, and handle or rethrow it based on that.

      try {
    const createdUser = await this.User.create(userInfo);
    // user was successfully created
    console.log(createdUser)
    // business logic goes here
    } catch (error) {
    if (error instanceof CreationError) {
    console.error(error) // from creation
    } else {
    throw error;
    }
    }

    Unfortunately, standard JavaScript (still) doesn't have syntax support for conditional exceptions.

    If your method doesn't return promises that are rejected with specific enough errors, you can do that yourself by re-throwing something more appropriate in a .catch() handler:

      try {
    const createdUser = await this.User.create(userInfo).catch(err => {
    throw new CreationError(err.message, {code: "USER_CREATE"});
    });

    } …

    See also Handling multiple catches in promise chain for the pre-async/await version of this.

  • Use then with two callbacks instead of try/catch. This really is the least ugly way and my personal recommendation also for its simplicity and correctness, not relying on tagged errors or looks of the result value to distinguish between fulfillment and rejection of the promise:

      await this.User.create(userInfo).then(createdUser => {
    // user was successfully created
    console.log(createdUser)
    // business logic goes here
    }, error => {
    console.error(error) // from creation
    });

    Of course it comes with the drawback of introducing callback functions, meaning you cannot as easily break/continue loops or do early returns from the outer function.



Related Topics



Leave a reply



Submit