I want to throw a specific exception for a block of code without creating a new class.
Is there any way to throw an exception with a specific code and catch it with this code identifier?
try {
//Do something
if(somevalue)
throw new Exception(667);
} catch (Exception e) {
if(e.getCode() == 667) {
//Do something
}
System.out.println("Something went wrong.");
}
I am not sure what is your use case. I assume your want to use codes to define some sort of state of your application so you can use IllegalStateException
You can use
try {
//Do something
if(somevalue)
throw new IllegalStateException("667")
} catch (IllegalStateException e) {
if("667".equalIgnoreCase(e.getMessage())) {
//Do something
}
System.out.println("Something went wrong.");
}catch(Exception e){
System.out.println("Unexpected error");
}
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.
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
}
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.
Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException) {
//can I throw this to the next level without eating it up in the last catch block?
} catch (Exception e) {
//default routine for all other exceptions
}
}
/Sidenote: the marked "duplicate" has nothing to do with my question!
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException se) {
throw se;
} catch (Exception e) {
//default routine for all other exceptions
}
}
you can do like this
try {
methodThrowingDifferentExceptions();
} catch (Exception e) {
if(e instanceof SpecificException){
throw e;
}
}
java.net.ConnectException extends java.net.SocketException
If I do the following, will it cater for both exceptions? ie if I catch a "parent" exception using instanceof, does that include any subclassed exceptions?
catch (Exception e)
{
if (e instanceof java.net.SocketException)
{
System.out.println("You've caught a SocketException, OR a ConnectException");
}
}
(and for the record, yes I know catching plain Exceptions is bad, just using it for this example ;) )
Exceptions are regular classes, so instanceof works fine for them.
But you don't need such a thing. The following achieves the same result:
try {
throw new ConnectException();
} catch (SocketException e) {
System.out.println("You've caught a SocketException, OR a ConnectException");
}
Yes, it will cater for both. Because ConnectionException IS A SocketException, it also is an instance of it.
Bozho already has given the right answer. I don't know your particular usecase, but you'd rather catch different exceptions:
try {
...
}
catch (SocketException ex) {
System.out.println("You've caught a SocketException, OR a ConnectException");
}
catch (Exception ex) {
...
}
I know that it's now a good way but if you want to do custom action in a many places in code you can do something like this:
public class ImageIOExecption extends Exception {
Exception ex;
public ImageIOExecption(Exception ex) {
this.ex = ex;
doCatch();
}
private void doCatch() {
System.err.println(ex.getClass());
if (ex instanceof java.net.SocketTimeoutException) {
System.out.println("You've caught a SocketTimeoutException, OR a ConnectException");
}
if (ex instanceof java.net.SocketException) {
System.out.println("You've caught a SocketException, OR a ConnectException");
}
}
}
public BufferedImage getBufferedImage() {
try {
BufferedImage srcImage = ImageIO.read(is);
is.close();
return srcImage;
} catch (Exception ex) {
new ImageIOExecption(ex);
}
return null;
}
Yes, that is how instanceof works. For exceptions it is more common to use something like this if you care about different exceptions. It works because the JVM will work down the list of catch statements in order and execute the first one that matches.
catch(ConnectException e)
{
//got ConnectException
}
catch(SocketException e)
{
/got a SocketException
}
catch(Exception e)
{
//got some other exception
}
Or below if you dont care about the difference between Connection and Socket Exception
catch(SocketException e)
{
//got a SocketException or a subclass e.g. ConnectionException
}
catch(Exception e)
{
//got another type of exception
}