Can we catch an exception type twice in the main method with different messages? I want to print out a different warning.
Ex:
try {
// some code
} catch (NumberFormatException e) {
System.out.println("Wrong input!");
} catch (NumberFormatException e) {
System.out.println("No valid number!");
}
You cannot catch the same exception type (like NumberFormatException) twice. I suggest you catch it once but in the catch block, you print two messages instead.
As i understand your comments you want to display the right message for your exception:
try {
// some code
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
You can´t catch the same exception twice.
What you can do is to throw a custom exception in your code and catch it if you want a different behaviour.
try{
...
throw new YourException(yourMessage);
}catch(YourException e){
}
You can´t catch the same exception twice.
Consider the following example,
try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
throw new SampleException(e);
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
Here,
Both handlers print an error message. The second handler does nothing else. By catching any IOException that's not caught by the first handler, it allows the program to continue executing.
The first handler, in addition to printing a message, throws a user-defined exception.
Related
I need to handle Exceptions which are raised by Catch block code in Java
Example, to "handle" an Exception:
try
{
// try do something
}
catch (Exception e)
{
System.out.println("Caught Exception: " + e.getMessage());
//Do some more
}
More info see: See: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
However if you want another catch in your try catch, you can do the following:
try
{
//Do something
}
catch (IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
try
{
// Try something else
}
catch ( Exception e1 )
{
System.out.println("Caught Another exception: " + e1.getMessage());
}
}
Be careful with nested try/catch, when your try catch is getting to complex/large, consider splitting it up into its own method. For example:
try {
// do something here
}
catch(IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
foo();
}
private void foo()
{
try {
// do something here (when we have the IO exception)
}
catch(Exception e)
{
System.out.println("Caught another exception: " + e.getMessage());
}
}
Instead of cascading try/catch (like in most of the other answers), I advise you to call another method, executing the required operations. Your code will be easier to maintain by this way.
In this method, put a try/catch block to protect the code.
Example :
public int classicMethodInCaseOfException(int exampleParam) {
try {
// TODO
}
catch(Exception e)
{
methodInCaseOfException();
}
}
public int methodInCaseOfException()
{
try {
// TODO
}
catch(Exception e)
{
//TODO
}
}
Do as you would do in an usual try/catch situation :
try{
throw new Exception();
}catch(Exception e1){
try{
throw new Exception();
}catch(Exception e2){
//do something
}
}
You can add new try catch block in your main catch block.
try
{
int b=10/0;
}catch(ArithmeticException e)
{
System.out.println("ArithmeticException occurred");
try
{
int c=20/0;
}catch(ArithmeticException e1)
{
System.out.println("Another ArithmeticException occurred");
}
}
I think the most clean way is to create method which is catching the exceptions occurs in its body. However it can be very dependent to the situation and type of code you are dealing with.
One example of what you are asking about is closing a Stream which is opened in a try-catch-finally block. For example:
package a;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream("temp.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
//TODO: Log the exception and handle it,
// for example show a message to the user
} finally {
//out.close(); //Second level exception is
// occurring in closing the
// Stream. Move it to a new method:
closeOutPutStreamResource(out);
}
}
private static void closeOutPutStreamResource(OutputStream out){
try {
out.close();
} catch (IOException e) {
// TODO: log the exception and ignore
// if it's not important
// OR
// Throw an instance of RuntimeException
// or one of it's subclasses
// which doesn't make you to catch it
// using a try-catch block (unchecked)
throw new CloseOutPutStreamException(e);
}
}
}
class CloseOutPutStreamException extends RuntimeException{
public CloseOutPutStreamException() {
super();
}
public CloseOutPutStreamException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CloseOutPutStreamException(String message, Throwable cause) {
super(message, cause);
}
public CloseOutPutStreamException(String message) {
super(message);
}
public CloseOutPutStreamException(Throwable cause) {
super(cause);
}
}
Here I illustrated a situation which the second level exception is occurring in the finally block, but the same can apply for the exceptions occur in the catch block.
In my point of view writing methods such as closeOutPutStreamResource can be useful because they are packaging a boiler plate code for handling very common exceptions and they are making your codes more elegant.
Also it would be your choice to catch and log the exception in closeOutPutStreamResource or to throw it to other layers of your program. But it would be more elegant to wrap this unimportant checked exceptions into RuntimeException without a need for catching.
Hope this would be helpful.
You can use try catch block any where in methods or in block, so you can write try catch in catch block as well.
try {
// master try
}catch(Exception e){
// master catch
try {
// child try in master catch
}catch(Exception e1){
// child catch in master catch
}
}//master catch
It's not necessary to have a nested try-catch block when catch block throws Exception as all answers here suggest. You can enclose the caller method with try-catch to handle that Exception.
I have been using Find Bugs in Eclipse and I can not figure out why some of the bugs are coming up or how to fix them. Any ideas or help would be great!
The first bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
The second bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
out.writeObject(accountMap.get(i));
I tried to change it to :
out.writeObject(accountMap.get(Integer.toString(i)));
The third bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Could not write file:" + fileName);
For the first bug this is with my try block as well. I am lost. I tried to follow you post below, but I am confused. Sorry, I am very new!
public ServerSolution() {
accountMap = new HashMap<String,Account>();
File file = new File(fileName);
ObjectInputStream in = null;
try {
if (file.exists()) {
System.out.println("Reading from file " + fileName + "...");
in = new ObjectInputStream(new FileInputStream(file));
Integer sizeI = (Integer) in.readObject();
int size = sizeI.intValue();
for (int i=0; i < size; i++) {
Account acc = (Account) in.readObject();
//CST316 TASK 1 CHECKSTYLE FIX
if (acc != null) {
accountMap.put(acc.getName(), acc);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
See FindBugs Bug Description:
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
How can I evaluate an exception? I mean this:
try{
catch(Exception ex){
if(ex == IOException){ //Error
System.out.println("IOException caught: " + ex.toString());
}
else if(){
}
....
}
I known there are other ways to achieve this. I just want to know if it's possible to compare an Exception "ex" to a defined Exception such as IOException.
The best practice would be to add different catch statements for each Exception you need to catch, in inverted class hierarchy order (narrower to broader).
try {
// TODO
}
catch(IOException ioe) {
}
catch(Exception e) {
}
Otherwise, you can always use instanceof.
catch(Exception ex) {
if (ex instanceof IOException) {
}
}
Notes
The latter can be slightly more useful with Java 7 styled multiple-exception catch blocks, e.g. catch (IOException | PatternSyntaxException ex).
As Codebender mentions, you can match the exact class instead of using instanceof by employing the following idiom:
if (ex.getClass().equals(IOException.class)).
The instanceof keyword is more powerful than exact class comparison, but may perform slower.
For instance, new FileNotFoundException() instanceof IOException returns true, because FileNotFoundException is a child class of IOException.
You can do more than one catch statements:
try
{
//code
}catch(IOException e)
{
//Code
}
catch (NoSuchFieldException e) {
//Code
}
....
Also, you can do it like this:
try {
//Code
} catch( IOException | NoSuchFieldException ex ) {
//Code
}
If you want to use the same code with more than one catch exceptions.
I expect it will be helpful for you!
You can use the instanceof operator. But keep in mind that you will check from the most specific to the most general.
Because a FileNotFoundException is also an IOException.
try{
//do stuff
}catch(Exception ex){
if(ex instanceof FileNotFoundException){
System.out.println("FileNotFoundException caught: " + ex.toString());
}else if(ex instanceof IOException){
System.out.println("IOException caught: " + ex.toString());
}
}
But a cleaner solution will be
try{
//do stuff
}catch(IOException ioe){
//handle IOException
}catch(Exception e){
//handle Exception
}
I am implementing exception handling in java with multiple exceptions.
Look at the following scenario:
Function f1 throws Exceptions e1, e2, e3 and e4
and Function f2 catches these.
Now I want to catch e1,e2 explicitly by catch(Exception e1 and e2) and the other exceptions should be caught all in the same block by catch(Exception e)
So e1 and e2 are a special case, and others are all general exceptions.
So will the following work?
try{
//some work`
} catch(ExceptionType1 e1) {
//do some special logging
} catch (ExceptionType2 e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}
My question is whether ExceptionType1(e1) will also be caught by Exception e?
The Spec writes:
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:
If that block completes normally, then the try statement completes normally.
If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
Therefore, at most one catch block will be executed.
For that to work you need to have catch blocks with different Exceptions
like NullPointerException NumberFormatException and the general exception will be caught by catch block with Exception parameter since Exception is the super class of all Exceptions
try{
//some work`
} catch(NullPointerException e1) {
//do some special logging
} catch (NumberFormatException e2) {
//do some special logging
} catch(Exception e) {
//do general logging for other exceptions
}
Using your code will catch all Exceptions in catch(Exception e1){...}
The other catch-blocks are unused. If you want to handle different Exception-types on different way you have to give the catch(...) other Exception-types.
Like
try{
}catch(IOException e1){
// Do sth
}
catch(NullPointerException e2){
// Do sth else
}
// and so on...
You cannot have multiple catch blocks with the same class i.e. Exception
If you have multiple Exceptions you need to create a separate class for each one and make your catch block for a specific class
Just be aware the order of your catch block must go from the more specific to the more generic class
e.g.
try {
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
} catch (Throwable e) {
System.err.println("Caught Throwable: " + e.getMessage());
}
So in the above code if the exception is of FileNotFoundException only the first catch will be executed. Otherwise the catch block with Exception is going to be executed for any instance of Exception class that was not caught in the previous catch blocks
At the end Throwable will catch anything that does not inherent from Exception such as Error
In the example below, you can see that the IOException (named FOURTH) exception cannot be caught using the outer catch clause. Why is that?
I know exceptions can be caught if its thrown in a nested try block, using outer catch.
If you change the b static variable value to false then you can see this.
But why cant we catch the exception thrown in a nested catch clause using an outer catch?
import java.io.*;
public class Exceptions {
static boolean b = true;
public static void main(String[] args){
try {
exceptions(b);
} catch (Exception e) {
System.out.println(e + " is handled by main().");
}
}
static void exceptions(boolean b) throws Exception{
try{
if(b) throw new FileNotFoundException("FIRST");
try{
throw new IOException("SECOND");
}
catch(FileNotFoundException e){
System.out.println("This will never been printed out.");
}
}
catch(FileNotFoundException e){
System.out.println(e + " is handled by exceptions().");
try{
throw new FileNotFoundException("THIRD");
}
catch(FileNotFoundException fe){
System.out.println(fe + " is handled by exceptions() - nested.");
}
try{
throw new IOException("FOURTH");
}
finally{}
}
catch(Exception e){
System.out.println(e + " is handled by exceptions().");
}
}
}
The output if b = true :
java.io.FileNotFoundException: FIRST is handled by exceptions(). java.io.FileNotFoundException: THIRD is handled by exceptions() - nested. java.io.IOException: FOURTH is handled by main().
The output if b = false:
java.io.IOException: SECOND is handled by exceptions().
But why cant we catch the exception thrown in a nested catch clause using an outer catch?
You can. The problem is that your last catch(Exception e) is at the same level of nesting which is why it doesn't catch an exception thrown in a previous catch block.
Try nesting your try/catch blocks like this
static void exceptions(boolean b) {
try {
try {
if (b) throw new FileNotFoundException("FIRST");
try {
throw new IOException("SECOND");
} catch (FileNotFoundException e) {
System.out.println("This will never been printed out.");
}
} catch (FileNotFoundException e) {
System.out.println(e + " is handled by exceptions().");
try {
throw new FileNotFoundException("THIRD");
} catch (FileNotFoundException fe) {
System.out.println(fe + " is handled by exceptions() - nested.");
}
// will be caught by the nested try/catch at the end.
throw new IOException("FOURTH");
}
} catch (Exception e) {
System.out.println(e + " is handled by exceptions().");
}
}
Your structure is some thing like this
try {
//operation
}
catch (Exce 1){ //catch 1
// throw IO
}
catch(Exce 2){ //catch 2
// print error
}
Here catch1 and catch2 are at same level, and the exception thrown from catch1 will not reach catch2.
Hence Your IOE will be thrown back to the caller . If you want to handle the exception with in the method, then follow some thing below
try{
try {
//operation
}
catch (Exce 1){ //catch 1
// throw IO
}
catch(Exce 2){ //catch 2
// print error
}
}
catch(Exce 3) {
// your IO will be caught here
}