Exception Handling in java to show user the catch error message from the nested method calls - exception

I have doubt in Exception handling in java,when the exception is thrown in the called method, how to show the catch error in the calling method

Yes, it is possible to catch exception inside called method, and then re-throw same exception back to caller method.
public String readFirstLineFromFile(String path) throws IOException {
try {
BufferedReader br = new BufferedReader( new FileReader (path));
StringBuilder lines = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
System.out.println("REading file..." + line);
lines.append(line);
}
return lines.toString();
} catch(IOException ex) {
System.out.println("Exception in called method.." + ex);
throw ex;
}
}
Note: It is not possible if you are using try with resources, and exception occurred inside resources itself like opening of file, or file not found. In that case exception will be directly thrown back to caller.

Related

Handling CompressorException in Java8 Streams

I have a static method for reading .bz2 files, it throws checked IOException and org.apache.commons.compress.compressors.CompressorException. The function signature is:
private static MyClass readFile(String fileName) throws IOException, CompressorException{
//…
}
Trying to use this method outright with Java8 streams gets compile time errors in Intellij;
unhandled exceptions: java.io.IOException, org.apache.commons.compress.compressors.CompressorException
So following advice from here, among others, I’ve tried the following but am stuck on how to handle the CompressorException object. Following it’s ctor I’ve tried as below but Intellij still complains the CompressorException is unhandled:
files.stream().forEach(i -> {
try{
readFile(i);
} catch (IOException e){
throw new RuntimeException(e);
} catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
});
Thanks
As #JB Nizet mentioned in the comment, you cannot throw any Exception from the lambda function inside foreach function.
You need to replace your current implementation:
catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
to either the following or not throw the RuntimeException at all.
catch (Throwable ex){
throw new RuntimeException("compressorException", ex);
}
The reason for the above behaviour is that the Stream.foreach() method has the following signature and doesn't throw any exception as part of the signature.
void forEachOrdered(Consumer<? super T> action)

Cannot handle FaultException by reflection invoking

I am preparing a client for WCF service.
I provoked an fault exception in some method on a service site. I mean:
throw new FaultException<sth>(new sth())
When I catch this exception in WPF appliction:
catch (FaultException<sth> ex)
{
// something
}
everything works very clearly.
My point is, that I made a reflection on the service interface.
var type = typeof (someServiceInterface);
type.GetMethods();
and I want to catch the FaultException, when I call the method service in this way
try
{
var singleMethod = //do sth to get method
var result = singleMethod.Invoke(proxy, parameters);
return result;
}
catch (FaultException<sth> ex)
{
//1
}
catch (Exception ex)
{
//2
}
But I catch an Exception in second catch, not in the first. The type of this Exception is "System.Reflection.TargetInvocationException". I am confused and I wonder what cause such kind of problem.

Java Unit test for Exception

public Document query(String uri) throws IOException, IllegalArgumentException
{
final HttpGet httpget = new HttpGet(uri);
final HttpResponse response = httpclient.execute(httpget);
final HttpEntity entity = response.getEntity();
Document doc = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(entity.getContent());
}
catch (SAXException e)
{
LOGGER.error(e);
throw new IllegalArgumentException("parse error" + e);
}
catch (ParserConfigurationException e)
{
LOGGER.error(e);
throw new IllegalArgumentException("parameter factor is invalid: " + e);
}
catch (IllegalStateException e)
{
LOGGER.error(e);
throw new IllegalArgumentException("null entity contetents" + e);
}
return doc;
}
#Test(expected = IllegalArgumentException.class)
public void testQuery_ParseExceptionThrown() throws Exception
{
String uri ="some uri";
EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class))).andReturn(mockResponse);
EasyMock.expect(mockResponse.getEntity()).andReturn(mockEntity);
EasyMock.expect(mockEntity.getContent()).andReturn(new ByteArrayInputStream(REPSONSE_EXAMPLE.getBytes()));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
EasyMock.expect(builder.parse(EasyMock.isA(InputStream.class))).andThrow(
new IllegalArgumentException("expected"));
EasyMock.replay();
class.query(uri);
}
error:
java.lang.IllegalStateException: calling verify is not allowed in record state
at org.easymock.internal.MocksControl.verify(MocksControl.java:181)
at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.verify(EasyMockMethodInvocationControl.java:120)
at org.powermock.api.easymock.PowerMock.verify(PowerMock.java:1650)
at org.powermock.api.easymock.PowerMock.verifyAll(PowerMock.java:1586)
at com.amazon.ams.test.AbstractUnitTest.verifyMocks(AbstractUnitTest.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.MethodRoadie.runAfters(MethodRoadie.java:145)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:99)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:296)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:112)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:73)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
I keep getting some errors like
java.lang.AssertionError: Expected exception: org.xml.sax.SAXException
java.lang.IllegalStateException: calling verify is not allowed in record state
There are 3 exceptions I need to write Junit test to get into the exception. Does anyone know how to use powermock or easymock class to write the unit test for it?
If you have a mock for the builder using easymock you can throw Exceptions instead of return values:
EasyMock.expect(builder.parse(myContent)).andThrow( myException);
Where myException is an Exception instance you want to throw (created by new MyException(...));
EDIT: example test code:
#Test
public void parseThrowsIllegalStateException(){
//... creating mock factory, builder and entity not shown
//create new Exception to be thrown
IllegalStateException expectedException = new IllegalStateException("expected");
EasyMock.expect(mockBuilder.parse(mockContent).andThrow(expectedException);
EasyMock.replay(...);
//exercise your system under test which tries to parse the entity's Content
//...
}
EDIT 2: now that you posted your actual test code I think the problem might be these lines:
EasyMock.expect(mockEntity.getContent()).andReturn(new ByteArrayInputStream(REPSONSE_EXAMPLE.getBytes()));
...
EasyMock.expect(builder.parse(new ByteArrayInputStream(malformed_XML.getBytes()))).andThrow(new SAXException("expected"));
I don't think ByteArrayInputStream overrides equals() so it is using Object.equals(). The ByteArrayInputStreams won't be equal so EasyMock will never throw the Exception
I would change the builder.parse() expectation to:
EasyMock.expect(builder.parse(EasyMock.isA(InputStream.class))).andThrow(new SAXException("expected"));
Which will throw when parse is called no matter what the inputStream is.
As a side note, your error message the mentioned "calling verify is not allowed in record state" but I don't see any calls to verify() or verifyAll() anywhere.

ServiceStack catch (WebServiceException ex) - has wrong ErrorCode

In my ServiceStack service, I throw an exception that has an inner exception. When I caught a WebServiceRequest on the client side, the ErrorCode was the inner exception type name.
This is bad for me because it doesn't allow me to respond to the specific exception type that was thrown on the server.
I'm failing to see why ServiceStack was designed this way. It's pretty typical to catch lower level exceptions and wrap them with more informative and sometimes end-user friendly exceptions.
How can I change the default behavior so it uses the surface level exception and not the inner-most?
After looking at the first example at https://github.com/ServiceStack/ServiceStack/wiki/Error-Handling, I decided to check out at DtoUtils.HandleException, which looks like this:
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
if (ex.InnerException != null && !(ex is IHttpError))
ex = ex.InnerException;
var responseStatus = ex.ToResponseStatus();
if (EndpointHost.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = GetRequestErrorBody(request) + ex;
}
Log.Error("ServiceBase<TRequest>::Service Exception", ex);
if (iocResolver != null)
LogErrorInRedisIfExists(iocResolver.TryResolve<IRedisClientsManager>(), request.GetType().Name, responseStatus);
var errorResponse = CreateErrorResponse(request, ex, responseStatus);
return errorResponse;
}
The very first instruction replaces the exception with it's inner exception. I'm not sure what the the thinking was with that. It seems counter intuitive to me and so I just re-implemented the method in my AppHost class, removing that first if statement block:
public override void Configure(Container container)
{
ServiceExceptionHandler += (request, exception) => HandleException(this, request, exception);
}
/// <remarks>
/// Verbatim implementation of DtoUtils.HandleException, without the innerexception replacement.
/// </remarks>
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
var responseStatus = ex.ToResponseStatus();
if (EndpointHost.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = DtoUtils.GetRequestErrorBody(request) + ex;
}
var log = LogManager.GetLogger(typeof(DtoUtils));
log.Error("ServiceBase<TRequest>::Service Exception", ex);
if (iocResolver != null)
DtoUtils.LogErrorInRedisIfExists(iocResolver.TryResolve<IRedisClientsManager>(), request.GetType().Name, responseStatus);
var errorResponse = DtoUtils.CreateErrorResponse(request, ex, responseStatus);
return errorResponse;
}
This is obviously not ideal, since I had to copy a bunch of code that is totally unrelated to the problem that I had with the original implementation. It makes me feel like I have to maintain this method whenever I update ServiceStack. I would love to here of a better way to accomplish this.
Anyway, I have the exception handling that I like in my client code:
catch (WebServiceException ex)
{
if (ex.ErrorCode == typeof (SomeKindOfException).Name)
{
// do something useful here
}
else throw;
}
It doesn't seem like you'll have to maintain a bunch of code. You're writing one method to implement your own error handling. You could try calling DtoUtils.HandleException(this, request, exception) in your own method and modify the HttpError object returned. Not sure you have access to change all properties/values you're looking for.
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
HttpError err = (HttpError)DtoUtils.HandleException(this, request, ex);
err.Reponse = ex.InnerException;
}

Exception handling and constructors

I am writing data to a file, when I write this data I want to do it so that if the file does not open it will give the user a message saying that something whent wrong. The way I do this is by calling the method to write, if it fails it returns false. That way I can prompt the user to do something to check what has happened.
However when I create the object I cant return anything from the constructor so I am a bit stumped about what I should do.
public class Writetofile {
BufferedWriter writer = null;
public Writetofile(String[]details) throws IOException{
String machine= details[0];
String date=details[1];
String start_time = details[2];
try{
File new_cal= new File("C:\\Activity_Calibrator\\log\\"+machine+"\\"+machine+date+".txt");
new_cal.getParentFile().mkdir();
FileWriter fwriter = new FileWriter(new_cal);
writer = new BufferedWriter(fwriter);
writer.write("Linear Calibratiton for " + machine + " carried out " + date+" ./n");
writer.close();
}
catch(Exception e){ in here I would like to be able to send a message back to m
code so that it can tell the user to check the folder etc}
}
when I call the record data if something goes wrong it will return a false to the calling class. and I can put a message.
public boolean recordData(String record) throws IOException{
try{
writer.append(record);
writer.close();
return true;
}
catch(Exception e){
return false;
}
}
}
}
A constructor should not DO anything. A constructor is an initialization phase closely tied to the allocation of an object.
Throwing exceptions, or doing anything in a constructor that might throw an exception is to be avoided.
Java does not separate the phases of allocation and initialization, no code, especially IO code should be in a constructor.