Unhandled exception error inspite of catching in a catch block - exception

I get an unhandled Exception type error for the following code, even though, as I understand it, I have handled the exception in the catch block.
class NewException extends Exception{
private String msg;
public NewException(String msg){
this.msg = msg;
}
public String getExceptionMsg(){
return msg;
}}
class CatchException {
public static void method () throws NewException{
try {
throw new NewException("New exception thrown");
}
catch (NewException e){
e.printStackTrace();
System.out.println(e.getExceptionMsg());
}
finally {
System.out.println("In finally");
}
}}
public class TestExceptions{
public static void main(String[] args){
CatchException.method();
}}

Your method() declares that it throws NewException. Whatever is inside that method is irrelevant:
public static void method () throws NewException{
//...
}}
public static void main(String[] args){
CatchException.method();
}}
The compiler sees that you are calling CatchException.method() in main() and that you are not handling it in any way (either catching or declaring main() to throw NewException as well. Thus the error.
The compiler doesn't care if you are actually throwing that exception or not. Have a look at ByteArrayInputStream.close() - there is no way it'll ever throw an IOException - but you still have to handle it since it's declared.

Related

mockito simulate test exception thrown by service

I am trying to test exception thrown from service when I use the instance of it.
Like I am trying to use Imock in Trans.class and use IMock method.
Below is the code
public class MockImpl implements IMock{
public String external(String str) throws Exception {
if(str.equals("throw")){
throw new Exception("Thrown exception.");
}
return str;
}
}
public class Trans {
private IMock mc;
public static int failed;
public String performTrans(String str) throws Exception {
return call(str);
}
private String call(String str) throws Exception {
mc = new MockImpl();
try {
return mc.external(str);
}
catch(Exception e){
failed++;
throw e;
}
}
}
In test class I am trying to do this
public class TestMock {
#Test
public void testMock() throws Exception {
Trans trans = mock(Trans.class);
IMock iMock = mock(IMock.class);
doThrow(new Exception()).when(iMock).external(any(String.class));
for(int i =0;i<10 ;i++){
trans.performTrans("any");
}
System.out.println(Trans.failed);
assertEquals(9, Trans.failed);
}
}
As I am new to this, I am not sure if my understanding is correct, what I am trying to achieve is
When I do # Trans.performTrans(String);
Then doThrow(new Exception()).when(iMock).external(any(String.class)); should happen. How can I tell Mockito or any test framework that The exception should be thrown should be simulated from the Imock service method, even if it is indirectly called.
UPDATE
After trying to test this way
#RunWith(MockitoJUnitRunner.class)
public class TestMock {
#Test
public void testMock() throws Exception {
Trans trans = new Trans();
IMock iMock = mock(IMock.class);
trans.setInter(iMock);
//doThrow(new Exception()).when(iMock).external(any(String.class));
trans.performTrans("abc");
verify(iMock).external(new String("a"));
System.out.println(Trans.failed);
assertEquals(9, Trans.failed);
}
}
I get this error.
Wanted but not invoked: iMock.external("a");
-> at com.app.TestMock.testMock(TestMock.java:32) Actually, there were zero interactions with this mock.
what could be wrong?

Why it is throwing compile time error?

Why this program throwing compile time error even though I have declared Ari class which extends Exception class.It is giving me output like "unreported exception Ari; must be caught or declared to be thrown".
class Ari extends Exception{ }
public class Main
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C ");
}
System.out.print("D");
}
public static void badMethod()
{
throw new Ari(); /* Line 22 */
}
}
This looks like Java, which uses "checked exceptions". Since your method can throw an Ari exception (in fact, it's guaranteed to), the method signature must declare this:
public static void badMethod() throws Ari {
throw new Ari();
}
This advises consuming code of the possibility of this specific exception so that it can be written to handle that exception.

How to mock a void private method to throw Abstract Exception with Powermock?

While writing unit test case for method someMethod1, I have a use case where I'm trying to ensure that an abstract exception (AnalysisException) is thrown when method (someMethod2) is called. Class under test is JdbcTemplateSampleImpl .
public class JdbcTemplateSampleImpl {
public void someMethod1() {
someMethod2();
}
private void someMethod2() throws AnalysisException {
// some code here
}
}
I am using PowerMockito to do like this
#Test(expected = com.test.AnalysisException.class)
public void abstractClassExceptionCheck2Test1() throws Throwable {
JdbcTemplateSampleImpl jdbcTemplateSampleImpl1 =
PowerMockito.spy(jdbcTemplateSampleImpl0);
PowerMockito.doThrow(mock(AnalysisException.class)).
when(jdbcTemplateSampleImpl1,"classCheck2");
jdbcTemplateSampleImpl1.abstractClassExceptionCheck2();
}
But while executing test case , i'm getting an error like this
java.lang.Exception: Unexpected exception, expected "com.test.AnalysisException" but was "java.lang.NullPointerException"
Mock the exception outside of the doThrow method call.
AnalysisException e = mock(AnalysisException.class);
PowerMockito.doThrow(e).
when(jdbcTemplateSampleImpl1,"classCheck2");

Exception handling - Try Catch ambiguous behaviour (??)

This is My code
from("direct:test-POST")
.doTry()
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
throw new NullPointerException(" Null value");
}
})
.doCatch(NullPointerException.class)
.log("${exception}") // This Prints NullPointer Exception
.process(new Processor() {
#Override
public void process(Exchange arg0) throws Exception {
System.out.println( arg0.getException() ); //This prints Null
}
})
.end();
Am using jetty:run to run this camel route.
How do I catch the exception. It prints the exception correct in log. but inside the processor, the exception is null. what am I missing
I would think the exception is found on a property on the exchange. Something like:
Throwable caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, NullPointerException.class);
assertNotNull(caused);

How to re-throw exception in AspectJ around advise

I have some methods which throws some exception, and I want to use AspectJ around advise to calculate the execution time and if some exception is thrown and to log into error log and continue the flow by re-throwing the exception.
I tried to achieve this by following but eclipse says "Unhandled Exception type".
Code-against whom AspectJ is to used :-
public interface Iface {
public void reload() throws TException;
public TUser getUserFromUserId(int userId, String serverId) throws ResumeNotFoundException, TException;
public TUser getUserFromUsername(String username, String serverId) throws ResumeNotFoundException, TException;
public TResume getPartialActiveProfileFromUserId(int userId, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException;
public TResume getPartialActiveProfileFromUsername(String username, int sectionsBitField, String serverId) throws ResumeNotFoundException, UserNotFoundException, TException;
}
Code AspectJ :-
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
Object ret;
Throwable ex = null;
StopWatch watch = new Slf4JStopWatch();
try {
ret = proceed();
} catch (UserNotFoundException e) {
ex = e;
throw e;
} catch (ResumeNotFoundException e) {
ex = e;
throw e;
} catch (Throwable e) {
ex = e;
throw new RuntimeException(e);
} finally {
watch.stop(thisJoinPoint.toShortString());
if (ex != null) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
numEx++;
}
}
return ret;
}
}
Please help why this AspectJ is not working.
you can avoid catching the exceptions and just use a try/finally block without the catch.
And if you really need to log the exception you can use an after throwing advice, like this:
public aspect AspectServerLog {
public static final Logger ERR_LOG = LoggerFactory.getLogger("error");
Object around() : call (* com.abc.Iface.* (..)) {
StopWatch watch = new Slf4JStopWatch();
try {
return proceed();
} finally {
watch.stop(thisJoinPoint.toShortString());
}
}
after() throwing (Exception ex) : call (* com.abc.Iface.* (..)) {
StringBuilder mesg = new StringBuilder("Exception in ");
mesg.append(thisJoinPoint.toShortString()).append('(');
for (Object o : thisJoinPoint.getArgs()) {
mesg.append(o).append(',');
}
mesg.append(')');
ERR_LOG.error(mesg.toString(), ex);
}
}
I'm afraid you cannot write advice to throw exceptions that aren't declared to be thrown at the matched join point. Per: http://www.eclipse.org/aspectj/doc/released/progguide/semantics-advice.html :
"An advice declaration must include a throws clause listing the checked exceptions the body may throw. This list of checked exceptions must be compatible with each target join point of the advice, or an error is signalled by the compiler."
There has been discussion on the aspectj mailing list about improving this situation - see threads like this: http://dev.eclipse.org/mhonarc/lists/aspectj-dev/msg01412.html
but basically what you will need to do is different advice for each variant of exception declaration. For example:
Object around() throws ResumeServiceException, ResumeNotFoundException, TException:
call (* Iface.* (..) throws ResumeServiceException, ResumeNotFoundException, TException) {
that will advise everywhere that has those 3 exceptions.
There is an "ugly" workaround - I found them in Spring4 AbstractTransactionAspect
Object around(...): ... {
try {
return proceed(...);
}
catch (RuntimeException ex) {
throw ex;
}
catch (Error err) {
throw err;
}
catch (Throwable thr) {
Rethrower.rethrow(thr);
throw new IllegalStateException("Should never get here", thr);
}
}
/**
* Ugly but safe workaround: We need to be able to propagate checked exceptions,
* despite AspectJ around advice supporting specifically declared exceptions only.
*/
private static class Rethrower {
public static void rethrow(final Throwable exception) {
class CheckedExceptionRethrower<T extends Throwable> {
#SuppressWarnings("unchecked")
private void rethrow(Throwable exception) throws T {
throw (T) exception;
}
}
new CheckedExceptionRethrower<RuntimeException>().rethrow(exception);
}
}