How to catch a thrown exception in the calling class - java

I got a method that throw an exception if I try to insert an existing object in DB.
public void addInDB() throws Exception {
if (isInBase()){
throw new Exception ("[ReqFamily->addInDB] requirment already in base");
}
int idParent = m_parent.getIdBdd();
idBdd = pSQLRequirement.add(name, description, 0, idParent,
ReqPlugin.getProjectRef().getIdBdd(), 100);
}
So when the exception is thrown I wanna catch it and display an error messsage in my managed bean.
PS: In my managed bean I just call the method :
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
ex.printStackTrace();
}
}

Its bad practice to catch or throw Exception. If any code you use throws a checked exception then just catch that specific exception, and try to minimize the size of your try-catch blocks.
class MyException extends Exception {
...
public void addInDB() throws MyException {
if (isInBase()){
throw new MyException ("[ReqFamily->addInDB] requirment already in base");
}
...
void addReq(Requirement req){
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
try {
req.addInDB();
} catch (MyException ex){
ex.printStackTrace();
}
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
}

Try this:
try {
req.addInDB();//here i want to catch it
} catch (Exception ex){
ex.printStackTrace();
}

You can try this:
void addReq(Requirement req){
try {
ReqFamily pReqParent = (ReqFamily) selectedNode.getData();
req.setParent(pReqParent);
req.addInDB();//here i want to catch it
DefaultTreeNode newReqNode = new DefaultTreeNode(req,selectedNode);
if (pReqParent!=null){
pReqParent.addRequirement(req);
}
} catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
If you wanna capture all of stacktrace to be show in display, you can use this:
catch (Exception ex) {
String
ls_exception = "";
for (StackTraceElement lo_stack : ex.getStackTrace()) {
ls_exception += "\t"+lo_stack.toString()+"\r\n";
}
JOptionPane.showMessageDialog(null, ls_exception);
}

Related

Analyze the following code, which exception does it display? (Exception handling, java)

class Test {
public static void main(String[] args) {
try {
String s = "5.6";
Integer.parseInt(s); // Cause a NumberFormatException
int i = 0;
int y = 2 / i;
}
catch (Exception ex) {
System.out.println("NumberFormatException");
}
catch (RuntimeException ex) {
System.out.println("RuntimeException");
}
}
}
The correct answer is that the program has a compilation error. I thought that the catch (Exception ex) would catch all exceptions including NumberFormatException, that it was a general exception that caught them all?
The block:
catch (Exception ex) {
System.out.println("NumberFormatException");
}
will catch all the exceptions, as the Exception class is the base class for all the exceptions.
When you catch Exception, you catch all the exceptions that extend Exception, which, all the exceptions do. Hence it produces the error that RuntimeException has already been caught

Java handle errors & exceptions

I have a class that allows to download a file from the internet:
public String download(String URL) {
try {
if(somethingbad) {
// set an error?
return false;
}
}
//...
catch (SocketException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch(InterruptedIOException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
Now, I am calling this function in another class and i want to show a message that will help me figure out why this will not work.
what can i do to display something like this?
HTTPReq r = new HTTPReq("http://www.stack.com/api.json");
if(r.err) {
showMessage(getMessage());
}
and the getMessage() will return the SocketException or IOException or even "empty url" if the URL is empty.
First of all I do not think you need all these:
SocketException, UnsupportedEncodingException, ClientProtocolException since they extend IOException
but if you want you can do this:
public String download(String URL) throws IOException, Exception {
try {
if(somethingbad) {
throws new Exception("My Message);
}
}
catch (IOException e) {
throw e;
}
}
And then in your other file:
try {
// some stuff
}
catch (Exception e) {
// do something with e.getMessage();
}
catch (IOException e) {
// do something with e.getMessage();
}
Instead of just doing e.printStackTrace() inside the catch blocks, throw the exception back like so:
throw e;
Then you can surround the calling code like so:
try {
HTTPReq r = new HTTPReq("http://www.stack.com/api.json");
} catch (Exception e) {
// Show error message
}

Java JUnit - Is it possible to determine if & which exception is thrown? [duplicate]

This question already has answers here:
How to do unit test for Exceptions?
(5 answers)
Closed 8 years ago.
I've got a method in a normal class that has a try with multiple catches:
Object returnObject = null;
try {
// do some stuff to set returnObject
}
catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (IllegalArgumentException ex) {
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
return returnObject;
In my UnitTest I would like to test if the method successfully went through the stuff in the try, without going into one of the caught Exceptions.
I know that if I didn't had a try-catch in my normal class' method, I could just use a try-catch with Assert.fail(...);, or an ExpectedException-tag in front of the test-method.
BUT, my method does have a try-catch, and I want to UnitTest if I successfully go through the try, without going to one of the catches. (As you can see in the code above, all my catches only have a ex.printStackTrace();)
PS: I also can't use the stuff in the try to test. So I can't check if returnObject is null after the method, because in this case I want it to be null (but without going to a catch). Otherwise I wouldn't asking this question.
Thanks in advance for the responses.
I think your Unit test doesn't have to know has exception been thrown and catched within method or not. Your unit test should test contract of your method. And it shouldn't concern about how this contract is implemented. So if contract of the method is return null if something bad happened and it's OK then test it in this way. If invoker should know was exception or not while method was executing and type of exception, then you may return some wrapper-object with method hasException();
You can assign exception name in a global String variable (use global - as you already returning an object), and compare the string in assert statement. If no exception case, returned string would be blank.
public static String message=""; // global variable
Object returnObject = null;
try {
// do some stuff to set returnObject
}
catch (NoSuchMethodException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (InstantiationException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (IllegalAccessException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (IllegalArgumentException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
message=ex.getMessage();
ex.printStackTrace();
}
return returnObject;
And assert -
assertEquals(ClassName.message.equalsIgnoreCase(""),true);
You can access the JVMs out put stream. We have done this with legacy code that unfortunately does not employ a logger, but prints all its information to System.out
For demonstration, have a look at this class that throws a given exception or none, if null is passed in the constructor. That thrown exception will be handled and printed to System.out, just like you explained in your question.
public class SystemOutClass {
private Exception exception;
public SystemOutClass(Exception exception) {
super();
this.exception = exception;
}
public Object doStuff() {
Object returnObject = null;
try {
doThrowException();
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (InvocationTargetException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return returnObject;
}
private void doThrowException() throws NoSuchMethodException,
InstantiationException, IllegalAccessException, InvocationTargetException,
Exception {
if (exception != null) {
throw exception;
}
}
}
The according test will switch the System.out to a known ByteArrayOutputStream, which then in turn can be checked for certain contents.
public class SystemOutTest {
private PrintStream defaultOutStream;
private ByteArrayOutputStream outStream;
#Before
public void setupStandardOutStream() {
outStream = new ByteArrayOutputStream();
defaultOutStream = System.out;
System.setOut(new PrintStream(outStream));
}
#After
public void cleanUpOutStream() {
System.setOut(defaultOutStream);
}
private String getConsoleOutput() {
return outStream.toString();
}
#Test
public void handleNoSuchMethodException() {
// given
SystemOutClass handlingClass = new SystemOutClass(new NoSuchMethodException());
// when
handlingClass.doStuff();
// then
getConsoleOutput().contains("java.lang.NoSuchMethodException");
}
}
If you have a specific part of a method that you'd like to test in isolation, refactor your class accordingly:
Object doSomeStuffAndPossiblyFail()
{
Object returnObject = null;
// do some stuff to set returnObject
return returnObject;
}
Object doSomeStuffAndReportFailureAsNull()
{
Object returnObject = null;
try {
returnObject = doSomeStuffAndPossiblyFail();
}
catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
....
return returnObject;
}
You're now free to test that doSomeStuffAndPossiblyFail completes without throwing any exceptions.

How to catch all exceptions except a specific one?

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;
}
}

I am having trouble try and catch method for NullPointerException. [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Code:
package exceptiona;
import java.io.IOException
public class ExceptionTest {
#SuppressWarnings("empty-statement")
public static void main (String[] args)
{
// call exceptionA
try{
throw new ExceptionA();
} catch (Exception e){
e.printStackTrace(};
System.out.println ("threw Exception A")
// call exceptionB
try{
throw new ExceptionB();
} catch (Exception e) {
e.printStackTrace(};
System.out.println ("threw Exception B")
// throw a NullPointerException
try{
throw new NullPointerException
} catch (NullPointerException){
nu
}
// throw IOException
try{
throw new IOException();
} catch (IOException io){
io.printStackTrace();
}
}
}
You have several syntax errors:
// throw a NullPointerException
try{
throw new NullPointerException();
} catch (NullPointerException npe){
npe.printStackTrace();
}
You should definitely learn java syntax in order to start coding.
Refer here for tutorials to get started
in the second catch, you have a syntax error:
change
e.printStackTrace(};
to
e.printStackTrace();
Generally speaking, you should avoid catching NullPointerException as they are runtime and show a wrong code logic.
What you should do is make sure you don't give null arguments to methods that should not be null.
public class ExceptionTest {
#SuppressWarnings("empty-statement")
public static void main(String[] args) {
// call exceptionA
try {
throw new ExceptionA();
} catch (Exception e) {
e.printStackTrace();
System.out.println("threw Exception A");
// call exceptionB
try {
throw new ExceptionB();
} catch (Exception e1) {
e1.printStackTrace();
System.out.println("threw Exception B");
// throw a NullPointerException
try {
throw new NullPointerException();
} catch (NullPointerException nu) {
}
// throw IOException
try {
throw new IOException();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
Your syntax is slightly off use this one:
try{
throw new ExceptionA();
} catch (Exception e){
e.printStackTrace();
System.out.println ("threw Exception A");
}
// call exceptionB
try{
throw new ExceptionB();
} catch (Exception e) {
e.printStackTrace();
System.out.println ("threw Exception B");
}
After this you use a word called: "nu"?
try{
throw new NullPointerException(); //missing ();
} catch (NullPointerException np){
//nu ?
System.out.println("threw NullPointerException");
}

Categories