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
}
}
Related
i'm struggling to figure out how to use the Closer utility from the guava library. Please see the code below.
One thing is, that the IndexWriter throws an IOException on both object initialization and close(). Therefore, the code in the finally and rethrow blocks is underlined.
The other question is, why do i have to catch Throwable instead of other exception types and do i have to rethrow the errors (i would prefer to log those at the spot)
`
int getDocumentsCount() {
Closer closer = Closer.create();
try {
IndexWriter iwriter = closer.register(openIndexWriter());
return iwriter.numDocs();
} catch (Throwable e) {
logger.error(e, e);
return -1;
} finally {
closer.close();
}
}
IndexWriter openIndexWriter() throws IOException {
return new IndexWriter(directory, analyzer, false,
IndexWriter.MaxFieldLength.UNLIMITED);
}
`
Thanks a lot
(stuck with Java 6)
From Guava's own explanation, you have to use Throwable, yes.
Here's their example snippet:
public void foo() throws IOException {
Closer closer = Closer.create();
try {
InputStream in = closer.register(openInputStream());
OutputStream out = closer.register(openOutputStream());
// do stuff with in and out
} catch (Throwable e) { // must catch Throwable
throw closer.rethrow(e);
} finally {
closer.close();
}
}
Note that they catch Throwable and rethrow it directly from the Closer instance.
As to why it is Throwable and not, let's say IOException or RuntimeException, it's because the Closer must know that an error occurred so that it can close the resources properly. All is only a matter of doing things proper. So it can work if you don't do it properly, but it's not guaranteed.
Not that if your method can throw MyOwnCheckedException, for instance, you have to declare them:
} catch (Throwable t) {
throw closer.rethrow(e, MyOwnCheckedException.class);
} finally {
closer.close();
}
Java 7 example, for comparison:
public void foo() throws IOException {
try (InputStream in = openInputStream();
OutputStream out = openOutputStream();
// do stuff with in and out
}
}
If you compare the Closer example with the Java 7 example, you can see that I still have to declare the IOException in the method signature.
For your case, this is what you have to do:
int getDocumentsCount() {
try {
Closer closer = Closer.create();
try {
IndexWriter iwriter = closer.register(openIndexWriter());
return iwriter.numDocs();
} catch (Throwable e) {
closer.rethrow(e);
} finally {
closer.close();
}
} catch (IOException e) {
logger.error(e, e);
return -1;
}
}
To avoid try-pyramids, I'd do the following:
int getDocumentsCount() {
try {
return doGetDocumentsCount();
} catch (IOException e) {
logger.error(e, e);
return -1;
}
}
int doGetDocumentsCount() throws IOException {
Closer closer = Closer.create();
try {
IndexWriter iwriter = closer.register(openIndexWriter());
return iwriter.numDocs();
} catch (Throwable e) {
closer.rethrow(e);
} finally {
closer.close();
}
}
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();
}
I want to get error message using java when exception are generated.
now I have java code with following scenario:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e)
}
}
method second(){
try{
my code
}catch(Exception e){
throw new Exception("Exception generate in second method",e);
}
}
now when the first method execute then I get only "Exception generate in second method" message but there is some other message printed on console by java so how to get that console error message.
Note: I have already try with e.getMessage(); and e.printStackTrace();
Every exception has a cause that you can get with getCause(). You can go recursively down them until you get to the root cause. Here is your example with a utility that dumps the exception with all its causes like the console does.
private void first() {
try {
second();
} catch (Exception ex) {
Log.e("CATCH", getExceptionDump(ex));
}
}
private void second() {
try {
throw new UnsupportedOperationException("We don't do this.");
} catch (Exception ex) {
throw new RuntimeException("Exception in second()", ex);
}
}
private String getExceptionDump(Exception ex) {
StringBuilder result = new StringBuilder();
for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
if (result.length() > 0)
result.append("Caused by: ");
result.append(cause.getClass().getName());
result.append(": ");
result.append(cause.getMessage());
result.append("\n");
for (StackTraceElement element: cause.getStackTrace()) {
result.append("\tat ");
result.append(element.getMethodName());
result.append("(");
result.append(element.getFileName());
result.append(":");
result.append(element.getLineNumber());
result.append(")\n");
}
}
return result.toString();
}
The message in the Exception constructor argument is not printed in the exception detail.
You can simply use this code to print the message :
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e.getMessage())
}
}
Hope this solves your problem
Why you cannot use print stack trace ?
Because A throwable contains a snapshot of the execution stack of its thread at the time it was created. (see Throwable)
It implies that, if you want to print the stack trace you need to use the printStackTrace() method BUT in your second method !
method second(){
try {
my code
} catch(Exception e) {
e.printStackTrace();
throw new Exception("Exception generate in second method",e);
}
}
Or using a the tricky method setStackTrace and using the printStackTrace() in first
method second(){
try {
my code
} catch(Exception e) {
Exception ex = new Exception("Exception generate in second method",e);
ex.setStackTrace(e);
throw ex;
}
}
method first(){
try {
second();
} catch(Exception e) {
e.printStackTrace();
}
}
You can print the cause of the exception you get. Try this:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e);
if (e.getCause() != null) {
System.out.println("Cause:> " + e.getCause());
}
}
}
I believe this is the console message you want to achieve:
Error:> java.lang.Exception: Exception generate in second method
Try this code, when the catch block of the second method throws an exception the second method should declare it as throws or put a nested try catch within the catch block.
The exception is propagated to the first() method which is handled by its catch block.
public class Test {
public void first() {
try {
second();
} catch (Exception e) {
System.out.println("Error:> " + e);
}
}
public void second() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception("Exception generate in second method", e);
}
}
public static void main(String ars[]) {
Test test = new Test();
test.first();
}
}
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());
}
}
when I debug the below code, there is an SmbException and goes catch block line sb.append(pLogger.reportError(pStr, e));, but it does not go into the method reportError().
what is the reason behind this. please advise if any changes.
try {
sfos = new SmbFileOutputStream(sFile);
} catch (SmbException e) {
sb.append(pLogger.rError(pathStr, e));
}
below is rError() method
public String rError(String pxString,Exception e){
String errorToMailStr=null;
abcd="Verifying # "+pxString+"::Error ["+e.getMessage()+"]";
logger.debug("Error when verifying # "+pxString+":Error ["+gMsg(e)+"]");
return abcd;
}
at line logger.debug("Issue "+pxString+":Error ["+gMsg(e)+"]");
is going to below method and ends.
public abstract class ReflectiveCallable {
public Object run() throws Throwable {
try {
return runReflectiveCall();
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
Based on what you have revealed here, there is a problem in getExceptionMsg()