The code is correct yet it needs try-catch.. why is that? - try-catch

I am very new to programming and I saw this code that runs perfect with try/catch.
I thought then try/catch is not necessary, as all I know that it just for checking errors and to change the message of the compile when in error.
But when I removed it the code renders many errors and refuse to compile. So what is try/catch is really doing here? because
The code:
import java.io.FileWriter;
public class html {
public static void main(String[] args) {
try{
FileWriter fw=new FileWriter("E:\\rrr.html");
fw.write("Welcome to javaTpoint.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}

The FileWriter class always throws an exception i.e, 'IOException',
Hence, whenever you use it IOException needs to be handled, so the
try-catch block is mandatory while using FileWriter.
What is an IOException?
An IOException is any unexpected problem the JVM encounters while attempting to run a program. Possible problems that it may encounter are:
attempting to read from a file that does not exist
attempting to write to a file that has an invalid name (a slash or a question mark in the title should do it)
attempting to read the next token in a file when there are no more tokens.
When an IOException is thrown, it means that whatever is throwing the exception (perhaps a try{}-catch block that reads data from a file) can throw an IOException, for example if the file is not found, corrupted, etc, or when the file is otherwise unable to be read, or any other of a list of issues that can occur with the IO package and it's extensions.

Related

How to Implement Retry analyzer in try catch Block?

Below is my code after got the exception immediately it should trigger one more time for execution but didn't execute.Without try,catch it was executing but after keep the code in try and catch RetryAnalyzer is not working as expected please anyone help me how to implement RetryAnalyzer in try,catch block
#Test(priority=4,enabled=true,retryAnalyzer=RetryAnalyzer.class)
public void TC_04() throws InterruptedException
{
try
{
extent=new
ExtentReports("/Users/anakin/workspace/Reports/MKE.html");
Login_Objects.Switch_PB2U(driver).click();
String screenshot_path = Screenshot.createScreenshot(driver);
String image = log.addScreenCapture(screenshot_path);
log.log(LogStatus.PASS, "To Stocks",image);
extent.endTest(log);
driver.closeApp();
}
catch(Exception e)
{
String screenshot_path = Screenshot.createScreenshot(driver);
String image = log.addScreenCapture(screenshot_path);
log.log(LogStatus.FAIL, "Verify Suggest Stocks ", image);
extent.endTest(log);
}
}
Catching exception in your complete test code is a bad practice. Even as in your case you are capturing screenshot in case of failure, you should use listener than catching exception.
Since retry analyzer works for failed tests, and you are cathing exceptions and thus supressing the errors, it might give the impression that your test never failed and thus the retryAnalyzer is not working.
Solution : Move code in Exception to Listeners and remove unnecessary Exception handling.

Put modified xml back into the message?

I'm using CXF to send messages with SOAP over JMS.
I'm trying to write a CXF Interceptor in the POST_MARSHALL phase.
I want to change some attributes when the xml is generated.
I know i can get the content from the message via
message.getContent(java.io.Writer.class).
This happens to be in the form of JMSConduit$1. Which - I think - is a StringWriter (if I debug my code I can see a buf field).
I can get the xml in String format and make my changes, but the problems is putting it back in the message.
I can not change the JMSConduit$1 to something else, otherwise CXF won't send it to the JMS Endpoint. (it must be a JMSConduit).
I can't find a way to put the modified xml back in a JMSConduit, which i can get through
message.getExchange().getConduit();
So, how can I put my modified xml back into the message/JMSConduit?
Finally found an answer. I used a FilterWriter.
public void handleMessage(Message message) throws Fault {
final Writer writer = message.getContent(Writer.class);
message.setContent(Writer.class, new OutWriter(message, writer));
}
class OutWriter extends FilterWriter {
#Override
public void close() throws IOException {
// Modify String (in xml form).
message.setContent(Writer.class, out);
}
}

First chance FileNotFoundException when calling IsolatedStorageFile.OpenFile

Somewhere in my code, I have this line:
return _store.OpenFile(path, fileMode);
With fileMode being sometimes FileMode.Create and sometimes FileMode.Open.
Everything works well, I always get a valid stream and if necessary, the file is correctly created.
But, I've just discovered in my VS output that I have the following message every time I call the method where the above line is:
A first chance exception of type 'System.IO.FileNotFoundException'
occurred in mscorlib.dll
I get this error when the file is created and I also get this error when the file is overwritten (and obviously exists).
I'm just curious about these errors since everything works perfectly.
Thanks,
EDIT: Same thing with new IsolatedStorageFileStream(...). Everything works fine but I still get the "first chance exception" message.
var isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isfs;
if (!isf.FileExists(_filename))
isfs = new IsolatedStorageFileStream(_filename, System.IO.FileMode.Create, isf);
else
isfs = new IsolatedStorageFileStream(_filename, System.IO.FileMode.Open, isf);
var writer = XmlWriter.Create(isfs);
xml.Save(writer);
writer.Close();
isfs.Close();
isfs.Dispose();
isf.Dispose();
Found the answer.
It's just how VS debugger works: for every exception caught by a {{catch}} block, a "first chance exception" message appears in the VS output.
So here, we can guess that, internally, the {{OpenFile}} method uses a try/catch block to check if the file exists.

why can't i write this camel route?

from("e1")
.split()
.method("bean", "m1")
.to("e2")
.end()
.split()
.method("bean", "m2")
.to("e3");
The compiler complains about the 2nd to. The reason is that for some reason, it thinks the second split returns ExpressionCaluse rather than ExpressionClause<SplitDefinition>, which causes the following method return type to be Object rather than SplitDefinition.
I tried it in Eclipse, and first I got the same result as you (with the eclipse code completion showing an error). Then I rewrote the route (e.g. splitting it up with assignments to
ProcessorDefinition pd = from("e1")....
pd.split()...
Then, back to the original code, so finally Eclipse got the idea correct and the error marker disappeared. I don't know if you was trying eclipse too?
#Override
public void configure() throws Exception {
from("e1")
.split()
.method("bean", "m1")
.to("e2")
.end()
.split().method("bean", "m2")
.to("e3");
}
I mean, it should work. The signature of split() in ProcessorDefinition is correct:
public ExpressionClause<SplitDefinition> split()
I guess this is a glitch somewhere in my dev. env. and probably yours too.. or something. Odd, anyway.

Can't read files from BlobStore

I have been trying to write and read files directly from the BlobStore, but it just doesnt work.
The issue is I open the file like file = fileService.getBlobFile(blobKey); and it doesn't throw any exception but right in the next line I call readChannel = fileService.openReadChannel(file, false); and that one throws a FileNotFoundException.
I'm confused as to why the first line did not throw the exception.
Here is the same issue
Unfortunately no one answered that question.
I haven't had any problems with writes or deletes, but I too get a FileNotFoundException when using openReadChannel(...) with an AppEngineFile.
I've tried using an AppEngineFile created from its constructor taking a complete path. I've tried using an AppEngineFile obtained from getBlobFile(...) like you do above. Either way, when the AppEngineFile is passed to openReadChannel(...) a FileNotFoundException is thrown.
My workaround was to let BlobstoreService.serve(...) do all the work of reading and sending the file. I suspect that using the FileService to read from an AppEngineFile isn't supported yet (I'm using 1.6.0), so reads must be done via the BlobstoreService (serve(...), fetchData(...), BlobstoreInputStream).

Resources