Disclosure: This text might include affiliate hyperlinks. While you buy, we might earn a fee.
The best way to catch a number of Exceptions in a single catch block
Although there may be an alternative choice to catch java.lang.Exception as an alternative of java.io.IOException and subsequently checked exceptions however that strategy is fragile as a result of it’ll additionally catch unintended exceptions.
Catching java.lang.Exception means your code is open for all form of exceptions, it is not thought-about pretty much as good apply. With a number of exception catch block in Java 7, you possibly can mix dealing with of those two exceptions at one place within the code.
Code earlier than Java 7
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.textual content.ParseException;
import java.textual content.SimpleDateFormat;
import java.util.Date;
/**
*
* Java program to catch a number of exception earlier than Java 7
*/
public class BeforeJava7{
public static void foremost(String args[]) {
attempt {
File file = new File(“take a look at.txt”);
FileInputStream fis = new FileInputStream(file);
BufferedReader bReader = new BufferedReader(new InputStreamReader(fis));
String str = bReader.readLine();
SimpleDateFormat format = new SimpleDateFormat(“DD/MM/YY”);
Date date = format.parse(str);
} catch (ParseException exception) {
//code to deal with ParseException
} catch (IOException exception) {
//code to deal with IOException
}
}
}
After Java 7, each of catch block will be changed with a easy a number of exception catch block, as proven under:
attempt{
//code
}catch(ParseException | IOException ex) {
// deal with ParseException and IOException right here.
}
Listed below are some extra vital options from Java 7 launch, you possibly can examine them right here:
Different Java 7 tutorials for Java programmer