Catch exceptions without a try block? - java

I have a lot of custom exceptions that I'm throwing in a specific cases in the code, and I'd like to have one catch block at the bottom of the method to handle them all.
All the exceptions are children of the Exception class CribbageException, so I'd like to have:
public void myMethod(){
if (whatever){
throw new CardException();
}
if (something else){
throw new InvalidCardException();
}
if (scenario 3){
throw new TwoCardsException();
}
catch (CribbageException e) {
System.out.println(e.getMessage());
}
}
But I'm getting a catch without try error.
Is there any way to use this type of exception handling?

Wrap all the throws inside a single try.
public void myMethod(){
try {
if (whatever){
throw new CardException();
}
if (something else){
throw new InvalidCardException();
}
if (scenario 3){
throw new TwoCardsException();
}
}
catch (CribbageException e) {
System.out.println(e.getMessage());
}
}

Related

Maintaining multiple Exception types while exception chaining in single try-catch

I have a function that throws several different types of custom Exceptions. I wish to catch these exceptions from that function, add some important information, and then throw the exception as their original type to pass up the caller chain (exception chaining). I would like this to be compact in a single catch if possible.
I know Java 7+ has the functionality to handle multiple Exception types and throw them while maintaining their type. However, when exception chaining I cannot catch and throw multiple Exception types in the same catch block without losing the type. Is it possible to throw an exception maintaining its original type in a single catch block that accepts multiple Exception types? Or do I have to split it into 3 nearly-equivalent (essentially redundant) catch blocks?
Example:
void thisWorks() {
try {
someFunction(); // throws ExceptionA, ExceptionB, ExceptionC
} catch (ExceptionA | ExceptionB | ExceptionC exception) {
throw exception; // still has the original ExceptionA/ExceptionB/ExceptionC type
}
}
void whatIWant() {
try {
someFunction();
} catch (ExceptionA | ExceptionB | ExceptionC exception) {
// This throws an Exception, not the original ExceptionA/ExceptionB/ExceptionC type.
// Is it possible to fit this in a single block like the thisWorks() function?
// Or do I have to split into 3 catch blocks just for the throw type?
throw new Exception("Important information here", exception);
}
}
i don't think there simple approach if you don't like multiple catch my approach would be something like this but to me one way or the other you still have some redundance either mutiple catch or do multiple instanceof your exception.
try {
someFunction()
} catch (Exception ex) {
if (ex instanceof ExceptionA) {
throw new ExceptionA("Important information here", ex);
} else if(ex instanceof ExceptionB){
throw new ExceptionB("Important information here", ex);
} else {
throw new ExceptionC("Important information here", ex);
}
}
public class MyThrowClass {
public static void main(String[] args) throws Exception {
try {
someFuntion(1);
} catch (Throwable t) {
throw new Exception("Important information here", t);
}
}
public static void someFuntion(int value) throws ExceptionA, ExceptionB {
if (value == 1) {
throw new ExceptionA("Exception A");
}
throw new ExceptionB("Exception B");
}
}

Catching non thrown checked exception

I have a code that invokes an external API via EJB and that API occasionally leaks an exception that is not part of the client kit, therefore resulting in ClassNotFoundException.
I have a try-catch block surrounding the call:
try {
thirdPartyLibrary.finalInvokeMethod();
} catch (SomeException exception) {
//Do something
} catch(
..
} catch (Exception exception) {
if (exception instanceof ClassNotFoundException) {
log.error("....");
}
}
I want to avoid using instanceof in catch, but if I add a separate catch clause for ClassNotFoundException, the compiler produces an error "Unreachable catch block", since thirdPartyLibrary.finalInvokeMethod(); doesn't throw ClassNotFoundException.
Is there a better way to address the issue?
I've found a workaround. I've wrapped the thirdPartyLibrary.finalInvokeMethod(); in another method that throws the checked exception. So I got a dedicated catch clause without a compiler error.
private someMethod() {
try {
callExternalAPI();
} catch (SomeException exception) {
//Do something
} catch(
..
} catch (ClassNotFoundException exception) {
log.error("....");
//Do something
} catch (Exception exception) {
//Do something
}
}
private void callExternalAPI() throws ClassNotFoundException {
thirdPartyLibrary.finalInvokeMethod();
}

How to specify a message on a method "throws" in Java?

Im trying to return a JOptionePane message dialog for each one of the possible throws on my method:
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException{
... content ...
}
Is there any way to do this?
You could try something like :
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException
{
try
{
...content...
}
catch(FileNotFoundException fnfEx)
{
throw new FileNotFoundException("File was not found");
}
catch(IOException ioEx)
{
throw new FileNotFoundException("I/O exception");
}
catch(InvalidFormatException invEx)
{
throw new FileNotFoundException("Invalid format errror");
}
}
Where you put the message you want in the new exceptions and you print the exception message in the JOptionPane.
wrap your code inside try catch. Inside catch block for each exception type throw the message specific to each exception
Using a Try-Catch you can catch any exception and return something when an exception occurs. You should do this for all of your cases.
public void add_note(String note){
try {
//code
} catch (FileNotFoundException e) {
//return something
}
}
Instead of throwing exceptions, handle each individually in your method:
public JOptionPane add_note(String note) {
try {
...
} catch (FileNotFoundException fnfe) {
return ...;
} catch (IOException ioe) {
return ...;
} catch (InvalidFormatException ife) {
return ...;
}
}
I'll suggest you an alternative approach, as no one mentioned it.
I'd use AOP to catch those exceptions and show to the end user. You'll write a simple aspect, and dont mess your code with try and catch blocks.
Here is an example of such aspect
#Aspect
public class ErrorInterceptor{
#AfterThrowing(pointcut = "execution(* com.mycompany.package..* (..))", throwing = "exception")
public void errorInterceptor(Exception exception) {
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor started");
}
// DO SOMETHING HERE WITH EXCEPTION
logger.debug( exception.getCause().getMessage());
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor finished.");
}
}
}
If you don't know what Aspect Oriented Programming is definitely go check it out, this is very powerfull concept (just like OOP), spend some time to learn it.
If you want to show a dialog with the JOptionPane.showMessageDialog do as follows:
public void add_note(String note){
try {
//code
} catch (FileNotFoundException | IOException | InvalidFormatException e) {
JOptionPane.showMessageDialog(frame, e.getMessage(), "Title", JOptionPane.ERROR_MESSAGE);
//manage the exception here
}
}

Call constructor from constructor and catch exceptions

I have a constructor which calls another constructor in the same class. The problem is I want to catch Exceptions and throw them onwards to the method that called the first constructor. Yet Java doesn't allow this as the constructor call must be the first statement in the constructor.
public Config(String fn) throws IOException, ExcFormattingError {
theFile = fn;
try { cfRead(); }
catch(FileNotFoundException e) {
//create a new config with defaults.
theConfig = defaultConfig();
create();
} catch (IOException e) {
throw new IOException(e);
} catch (ExcFormattingError e) {
throw new ExcFormattingError();
}
fixMissing(theConfig);
}
public Config() throws IOException, ExcFormattingError {
try {
//Line below is in error...
this("accountmgr.cfg");
} catch (IOException e) {
throw new IOException(e);
} catch (ExcFormattingError e) {
throw new ExcFormattingError();
}
}
If someone could explain how I could do this that would be good. A bonus would be knowing why the language has to behave this way, because that is always interesting.
You don't need those try-catch block inside the constructor (in fact, you can't write it there, as you already figured out). So, change your constructor to:
public Config() throws IOException, ExcFormattingError {
this("accountmgr.cfg");
}
In fact the catch block in your constructor was hardly doing anything productive. It was just re-creating an instance of the same exception, and throwing it. That is really not needed given the fact that, if the exception is thrown, it will automatically propagated to the caller code, where you can handle the exception.
public void someMethod() {
Config config = null;
try {
config = new Config();
} catch (IOException e) {
// handle it
} catch (ExcFormattingError e) {
// handle it
}
}
Having said that, it is rarely a good idea to throw a checked exception from the constructor, even worse handling them in the caller code.
If the exception is thrown, and you handle it in the calling method. Then you are simply ignoring the fact that your instance is not completely initialized. Proceeding with that instance further will result in some unexpected behaviour. So, you should avoid it really.

DRY for Exception Wrapping

I'm working on some server-side code that wraps all exceptions before passing them to the client side, due to this all client facing methods have the following code
try{
DoSomething();
} catch (ExceptionA e) {
throw new CustomException(AType, e);
} catch (ExceptionB e) {
throw new CustomException(BType, e);
} catch (Exception e) {
throw new CustomException(Unexpected, e);
}
to have this repeated in every method seems to violate the DRY principle and I was wondering what the best way to refactor it would be. For instance I was thinking a wrapper method such as:
private void wrapException(Exception e) {
if (e instanceof ExceptionA) {
throw new CustomException(AType, e);
}
etc...
Take a look at AspectJ soften exception.
Also look at Guava's Throwables.
There is also Lamboks sneaky exception.
The other option is to use Anonymous object instances aka closures.
public abstract class Wrapper {
public void execute() {
try {
// do some boiler plate before
this.wrap();
// do some boiler plate after.
} catch (ExceptionA | ExceptionB ex) {
Type t = determineType(ex);
throw new CustomException(t, ex);
}
}
public void abstract wrap();
}
Now in your code you do something like:
new Wrapper() {
public void wrap() {
DoSomething();
}
}.execute()
This is possible in Java7 and up:
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Copy-paste example from above doc:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
This is one way to go about it:
Exception caughtEx = null;
String extraInfo = null;
try{
DoSomething();
} catch (ExceptionA e) {
caughtEx = e;
extraInfo = AType;
} catch (ExceptionB e) {
caughtEx = e;
extraInfo = BType;
} catch (Exception e) { // catching Exception is usually a bad idea, just let it bubble up without catching...
caughtEx = e;
extraInfo = Unexpected;
}
if (caughtEx != null) throw new CustomException(extraInfo, caughtEx);

Categories

Resources