how can i catch 2 or more exception in same time ? Should i use trycatch-block for each all issue ?
For example, i couldn t catch b.charAt() to "Null Pointer Exception" after arithmeticException.
try{
int a = 6 / 0 ;
String b = null;
System.out.println(b.charAt(0));
}
catch(NullPointerException e){
System.out.println("Null Pointer Exception");
}
catch(ArithmeticException e){
System.out.println("Aritmetic Exception ");
}
In Java SE 7 and later, you actually can catch multiple exceptions in the same catch block.
To do it, you write it this way:
try{
// Your code here
} catch (ExampleException1 | ExampleException2 | ... | ExampleExceptionN e){
// Your handling code here
}
Besides that, you can use an extremely general catching exception like:
try{
// code here
} catch (Exception e){
// exception handling code here
}
But, that is a discouraged practice. ;)
Resources: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html (Oracle Documentation).
Related
This question already has answers here:
Can I catch multiple Java exceptions in the same catch clause?
(10 answers)
Closed 1 year ago.
public void run() {
final V value;
try {
value = getDone(future);
} catch (ExecutionException e) {
callback.onFailure(e.getCause());
return;
} catch (RuntimeException | Error e) {
callback.onFailure(e);
return;
}
callback.onSuccess(value);
}
I think the "|" computation is a kind of bit computation, and it can be applied to byte, int, long and so on. But what's the meaning when "|" symbol applied to some java classes?
RuntimeException | Error e
It is to catch multiple exceptions inside a single catch block
try{
}
catch(Exception1 | Exception2 | Exception2 e){
callSomething()
}
equivalent to :
try{
}
catch(Exception1 e){
callSomething()
}
catch(Exception2 e){
callSomething()
}
catch(Exception3){
callSomething()
}
this
catch (RuntimeException | Error e) {
means you are actually defining a block for catching either a RuntimeException OR an Error
that was introduced since java7
here more info about it:
https://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
the explained pretty well
Consider the following example, which contains duplicate code in each of the catch blocks:
catch (IOException ex) {
logger.log(ex);
throw ex;
catch (SQLException ex) {
logger.log(ex);
throw ex;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.
The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
The output is correct but it's followed by an EOFException. I read the documentation but still i don't know how to solve this
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.bin"))){
for(Ser s = (Ser)ois.readObject(); s!=null; s=(Ser)ois.readObject() )
System.out.println(s);
}catch (IOException | ClassNotFoundException e){
e.printStackTrace();
}
You are assuming that readObject returns null if there is no data, but in fact it throws EOFException. The simplest fix is just to catch the exception:
try(...) {
for(;;) {
Ser s = (Ser)ois.readObject();
System.out.println(s);
}
} catch(EOFException e) {
// normal loop termination
} catch(IOException | ClassNotFoundException e){
// error
}
Be aware that some people and coding standards consider it bad practice to have an exception thrown in non-error conditions, like reaching the end of input in this case.
Why bitwise or is used here?
try
{
//some errorprone code
}
catch(NullPointerException |NumberFormatExceptioon e)
{
////handling the exception
}
That's not a bitwise operator in this case. It's the syntax of catching multiple exceptions.
Feature added in Java 7.
https://docs.oracle.com/javase/8/docs/technotes/guides/language/catch-multiple.html
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).
Before java 7, you need write
try{
//some errorprone code
}catch (NullPointerException ex) {
//handle
} catch (NumberFormatExceptioon ex) {
//handle
}
Look, they simplified it right ?
Background
I have a case where my logic requires surround with try/catch, I have a lots of catch clauses, which makes my code a bit ugly. What I do in catch clause is only log the error using log4j.
Question
Is it ok to use one catch clause with parent exception type instead of bunch of catch clauses?
Instead of this:
try{
//some statements
} catch (KeyStoreException e) {
LOGGER.error(e);
} catch (CertificateException e) {
LOGGER.error(e);
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e);
} catch (FileNotFoundException e) {
LOGGER.error(e);
} catch (IOException e) {
LOGGER.error(e);
} catch (UnrecoverableKeyException e) {
LOGGER.error(e);
} catch (NoPropertyFoundException e) {
LOGGER.error(e);
}
using :
try{
//some statements
} catch (Exception e) {
LOGGER.error(e);
}
Which one is better?
When catch exceptions I usually find that more specific is better, that being said typing out all of those different blocks that do the same thing can get really annoying. Thankfully in the Java 7 release a try-catch notation was added where you can specific multiple exceptions for a single block:
try{
//some statements
} catch (KeyStoreException |
CertificateException |
NoSuchAlgorithmException |
FileNotFoundException |
IOException |
UnrecoverableKeyException |
NoPropertyFoundException e) {
LOGGER.error(e);
}
This sounds like what you are looking for, but there is more detailed information in the Oracle docs: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Is it ok to use one catch clause with parent exception type instead of bunch of catch clauses?
Hunter has provided the correct solution for Java 7 and later.
For Java 6 and earlier, it depends on the parent exception that you choose. Exceptions like Throwable, Exception and RuntimeException are far too general. If you catch these, you can end up accidentally catching (and then mishandling) exceptions that you should allow to propagate. For example, your code would catch NullPointerException that you should probably not attempt to recover from ... like that.
The first version is more correct / more robust than the second version, and that better even if it looks ugly.
Of course, the real answer depends on what happens after you have caught and logged the exception. If what happens next is appropriate for all exceptions, then the second version is (arguably) preferable. For instance, it could be appropriate to catch all exceptions, log them and then call System.exit(...).
Hello,
In Java if a method like BufferedReader.read() says it can throw an IOException and I try to catch a FileNotFoundException and an IOException in two catch blocks, what catch blocks will be entered if the file doesn't exist?
Does it enter only the most specific or both?
The first coded catch that matches the exception will be entered.
Edited to incorporate comment from Azodius
For example:
try {
bufferedReader.read();
} catch (FileNotFoundException e) {
// FileNotFoundException handled here
} catch (IOException e) {
// Other IOExceptions handled here
}
This following code does not compile:
try {
bufferedReader.read();
} catch (IOException e) {
// All IOExceptions (and of course subclasses of IOException) handled here
} catch (FileNotFoundException e) {
// Would never enter this block, because FileNotFoundException is a IOException
}
Compiler message says:
Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException
Only the first catch block encountered where the exception type of the catch block matches the type of the exception being thrown will be run (more specifically, the first catch block where (e instaceof <exception type>)==true will be run). None of the other catch blocks will be run.
For example
try{
BufferedReader.read();
}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
catch(IOException e){System.out.println("IOException");}
Will print FileNotFoundException if BufferedReader.read() throws a FileNotFoundException.
Note that the following doesn't actually compile:
try{
BufferedReader.read();
}
catch(IOException e){System.out.println("IOException");}
catch(FileNotFoundException e){System.out.println("FileNotFoundException");}
because Java realizes that it is not possible for the FileNotFoundException to be caught because all FileNotFoundExceptions are also IOExceptions.
The first one which is suitable for that type of exception (and only that). So if you catch the two exception types above in the order you list them, a FileNotFoundException will be caught.
Specific exception is caught first. and it's a compile time error if generic exception is caught befor specific one.