Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try-catch block

I have a class with different methods doing the same thing reading a file. I want to use try-catch block for exception handling. I want to ask if there is any way so that all methods will go inside a single try block as every method will give same exception "file not found"..

like image 977
userhead Avatar asked May 11 '11 11:05

userhead


People also ask

What is try catch block in C++?

Try/Catch Block. Definition - What does Try/Catch Block mean? "Try" and "catch" are keywords that represent the handling of exceptions due to data or coding errors during program execution. A try block is the block of code in which exceptions occur. A catch block catches and handles try block exceptions.

What is a catch-block?

A catch -block contains statements that specify what to do if an exception is thrown in the try -block. If any statement within the try -block (or in a function called from within the try -block) throws an exception, control is immediately shifted to the catch -block. If no exception is thrown in the try -block, the catch -block is skipped.

How to handle exceptions in a try-catch block?

Thank you. Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

What is the use of try catch in Java?

Java try-catch block. Java try block. Java try block is used to enclose the code that might throw an exception. It must be used within the method. If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.


1 Answers

My preferred way of handling that would be to call a common method from all of them, so each (individually) looks like:

try {
   // code
} catch(SomeExceptionType ex) {
   DoSomethingAboutThat(ex);
}

However, you can also do it with delegates, i.e.

void Execute(Action action) {
    try {
       // code
    } catch(SomeExceptionType ex) {
       // do something
    }
}

and

Execute(() => {open file});
like image 159
Marc Gravell Avatar answered Oct 20 '22 22:10

Marc Gravell