Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-catch every line of code without individual try-catch blocks

I do not currently have this issue, but you never know, and thought experiments are always fun.

Ignoring the obvious problems that you would have to have with your architecture to even be attempting this, let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.:

WidgetMaker.SetAlignment(57);
contactForm["Title"] = txtTitle.Text;
Casserole.Season(true, false);
((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true;

Multiplied by a hundred. Some of these might work, others might go badly wrong. What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code.

How would you attempt to tackle this problem?

like image 806
tags2k Avatar asked Sep 22 '08 19:09

tags2k


People also ask

Can catch block be written without try block?

We can't write any code between try-catch-finally block. We can't have catch or finally clause without a try statement. We can have multiple catch blocks with a single try statement. try-catch blocks can be nested similar to if-else statements.

Can you have multiple try blocks without catch?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.

Is it bad practice to use try catch?

Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.

Can you have multiple catches for one try?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.


1 Answers

public delegate void VoidDelegate();

public static class Utils
{
  public static void Try(VoidDelegate v) {
    try {
      v();
    }
    catch {}
  }
}

Utils.Try( () => WidgetMaker.SetAlignment(57) );
Utils.Try( () => contactForm["Title"] = txtTitle.Text );
Utils.Try( () => Casserole.Season(true, false) );
Utils.Try( () => ((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true );
like image 113
Lost Plugin Writer Avatar answered Oct 06 '22 19:10

Lost Plugin Writer