I am new to programming, and am currently in product management. So I am learning the ropes. I tried this statement:
public class Tuna {
Formatter f;
public void createfile(){
try{
f = new Formatter("help.text");
f.format("%s%s", "firstname ","lastname");
}
catch (Exception e){
System.out.println("You got an error ");
}
}
Now the first statement executes and a file is created, but the second statement does not execute by creating an entry into the file.
At the same time when I created a method called createrecord() and inserted the f.format(..); statement it worked.
Can anyone tell me how all of this works?
First, you should never catch Exception. Instead, be as specific as possible in watch exception type to catch. In this case it would be FileNotFoundException.
Secondly, you have to close your formatter so it will actually release the file and make the edits.
Example that works for me:
public class SO41304560 {
public static void main(String[] args) throws Exception {
try {
Formatter formatter = new Formatter("c:/Temp/test.txt");
formatter.format("%s%s", "firstname ","lastname");
formatter.close();
} catch (FileNotFoundException e) {
throw new Exception(e);
}
}
}
As Formatter is AutoClosable, you can also use a try with resources:
public class SO41304560 {
public static void main(String[] args) throws Exception {
try (Formatter formatter = new Formatter("c:/Temp/test.txt")){
formatter.format("%s%s", "firstname ","lastname");
} catch (FileNotFoundException e) {
throw new Exception(e);
}
}
}
Yes, you can put as much code as your heart desires in a try block (but there's something to be said about how much and what you SHOULD).
First order of business, and this should always be the first thing you check. Is your filename right? Does it have a prefix of .text or .txt?
Also don't forget to flush your formatter once you're done. Call f.flush(); when you're done with it
Yes, there is no limit on the quantity of the code to put inside a try block, it depends on how much you need to control the execution of the code based on the exceptions.
Related
I wrote a method to close write to a file.
However, a senior developer suggested me to close the file inside the finally block.
This is the method I have:
private static void writetoFiles(String error) {
try {
File file = new File("errorcode.txt");
if (!file.exists()) {
file.createNewFile();
} else {
FileWriter updateerrorcode = new FileWriter("errorcode.txt");
updateerrorcode.write(error);
updateerrorcode.close();
}
} catch (IOException e) {
}
}
I read many answers in stackoverflow but all of them seemed a bit too complicated for a simple case like mine.
Any suggestions how should I go about this?
The cleanest approach would be to do it using the try-with-resources statement as shown below:
private static void writetoFiles(String error) throws IOException {
//...
try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
updateerrorcode.write(error);
}
//...
}
Do not catch an exception in a method if it can not handle it:
If the method, writetoFiles can not handle the exception, it should throw the same so that the calling method can handle it appropriately.
Use a try-with-resource statement:
private static void writetoFiles(String error) {
try {
File file = new File("errorcode.txt");
if (!file.exists()) {
file.createNewFile();
} else {
try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
updateerrorcode.write(error);
}
}
} catch (IOException e) {
// TODO: Handle error condition
}
}
To point out a separate issue...I think your logic is wrong in your example. If the output file doesn't exist, all your code does is create the file. Only if the file already exists does it write the error text to it. I expect that you want to write the text in either case. If this is true, you don't need the createNewFile call at all, as the FileWriter class will create the file if it doesn't already exist. So I think what you really want is this:
private static void writetoFiles(String error) {
try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
updateerrorcode.write(error);
} catch (IOException e) {
// TODO: Handle error condition
}
}
This will cause the writer to be properly closed in both the normal execution case and the error throw case. I assume that in your actual code, you'll do something with that IOException when it is caught. I can't know what you want to do there, so I won't propose anything.
If you want to strictly use a finally block, you can do this instead:
FileWriter updateerrorcode = new FileWriter("errorcode.txt");
try {
updateerrorcode.write(error);
}
catch (IOException e) {
// TODO: Handle error condition
}
finally {
updateerrorcode.close();
}
This is the only option you would have had in earlier versions of Java, prior to the addition of the try-with-resource construct. In this second method, you might want to catch an error from close(), but in all of my 25+ years of experience with Java, I don't recall a close() call on a file failing. I guess you'd get that if you were out of disk space on your target volume and so close() couldn't flush the stream's write buffer. This issue is a distinct advantage of the newer method...failure to close the file won't affect the throw/catch of an exception thrown by the write() call.
So I'm working on a little project in Java and I've come down to the main method and I'm unsure how I should handle try-catching exceptions correctly.
Should I be:
Try-catching specific lines of code that I know will probably throw an exception?
Like:
public class Stuff {
public static void main(String[] args) {
try {
// code that will probably throw exception 1 or 2
} catch (exception1 e) {
// handle exception 1
} catch (exception2 e) {
// handle exception 2
}
//rest of code that probably won't throw any exceptions
}
}
OR
Try-catching the whole main method even if some of the code in the try block will not throw an exception? Like:
public class Stuff {
public static void main(String[] args) {
try {
// code that will probably throw exception 1 or 2
// rest of code that probably won't throw any exceptions
} catch (exception1 e) {
// handle exception 1
} catch (exception2 e) {
// handle exception 2
}
}
}
One thing to consider is whether or not the code running after the catch block would still be valid if an exception was thrown. For example, consider the following method:
private void readFile()
{
List<String> lines = null;
try
{
lines = Files.readAllLines(Paths.get("/to/my/file.txt"));
}
catch (IOException e)
{
// log exception...
}
for (String line : lines)
{
System.out.println(line);
}
}
If readAllLines throws that IOException, then the code after the catch block will throw a NullPointerException.
There's a bigger question of deciding when to catch vs re-throw an exception. I answer it by asking myself this question:
"Can my method fulfill its contract if this exception is thrown?"
YES: Handle the exception and continue to fulfill the method's contract.
NO: Re-throw the exception (either in throws clause or wrap in a more appropriate exception type).
For example, with this method,
public static List<String> readAllLines(Path path) throws IOException
if the file does not exist, it cannot return a list of the lines of the file, so it throws an IOException.
On the other hand, this method
public static boolean deleteIfExists(Path path) throws IOException
does not throw an exception if the file does not exist (it instead returns the boolean to tell you what happened). One way to think of the contract of this method is, "after this method executes, there will not be a file at path". So in this case, if the file does not exist, the contract is still fulfilled.
That depends - should the non-exceptional code be executed if either exception is raised? This isn't a "best practices" question, this is a "what are your specifications?" question.
Suppose your code looks like this:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
someValue = defaultValue;
}
// Continue, possibly using the default value
In a case like this, you should wrap only the single line. On the other hand, maybe your code looks like this:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
log.fatal("The universe is crashing! Run for your lives!");
System.exit();
}
// Continue, assuming that parsing succeeded
In that case, it's a stylistic choice. Either approach is valid, though with such an extreme failure as in this example it might be better to simply declare that the method throws something and forget the try/catch entirely. In fact, whatever your handling code is, if the only thing left for your method to do after it is to bail out, you should consider omitting the try/catch and using a throws clause instead.
This third case, however, is objectively wrong:
String someValue;
try {
someValue = parseSomething();
} catch (ParseFailureException e) {
log.info("something strange happened");
// Don't bother the calling code with the exception, it can't handle it.
}
// Continue, assuming that parsing succeeded
In a case like that, the continuation code must go inside the try block.
I’m running a code that throws an exception,I want run the exception code continuously whenever the exception is thrown it has go to starting and should start the program from starting.
Here is my exception method and main
You need to put the try / catch in a loop; e.g. something like this:
public static void main(String[] args) {
while (true) {
try {
// do something
} catch (Exception ex) {
// report ex
}
}
}
Now, the above will repeat the // do something code block until the program is killed, which may not be what you want. If you wanted to terminate when the // do something succeeds, then one solution would be to add a break statement at the end of it. Others could be to set a flag and loop until the flag is set, or even call System.exit(...).
I think I get what you're wanting.
You can explicit throw a generic exception in your try statement which prevents having to generate one through "bad code". You can also pass the "message" you wan to display to this exception and print it out in the catch statement along with the done. Since the exception is handled in the exc() method you won't need the try/catch statement in the main method. It could just be one line.
exc();
public static void exc() {
for(;;){
try{
throw new Exception("Exception");
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Done");
}
}
}
Try this one..
public static void main(String[] args) {
Test_exception_main u = new Test_exception_main();
while(true){
try{
u.exc();
}catch(Exception e){}
}
}
What should we do in catch block when we can't do anything useful for program work recovery? Say it's simple program, so Logging does not suitable too. For example:
public class Test {
public static void main(String[] args) {
try {
Scanner in = new Scanner(Paths.get("SomeFile.txt"));
//...
} catch (IOException exc){
//System.out.println("Error"); — erroneous, right?
}
}
}
If it's a simple program, either do nothing (don't catch the exception, add throws clause to your main method), or print some error message in the catch block (preferably to System.err). The latter option only makes sense if there is no more code after the catch block (since you don't want to execute any code after the exception is caught).
I have a Java Program where I get data from a different source. some times while reading I see Exception and the program is exiting.
Mine is in a program that runs every 10minutes.
Public static void main(Strings[] args)
{
...readsource();
}
Private static void readsource() throws IOException
{
...
}
Issue:
I am able to get/See the Exception. But I want the program to continue
To that what is the best logic? I dont see try-catch-finally also is not addressing ..I want the program to continue even after seing the exception (I mean the next iteration should continue). This looks to be a Basic issue not sure how to address this...
Then you need to catch the exception, which you are currently not doing.
try {
readsource();
} catch (IOException e) {
// do something, never catch an exception and not do anything
}
//continue.
Note that exceptions usually indicate something is wrong. Unless you are going to do something about the exception, it might be better to fix the condition causing the exception....
You have to provide an error handler in your method, i.e. surround the call to readsource() with a try-catch block.
public static void main(Strings[] args)
{
try{
...readsource();
}
catch(IOException ioe){
//handle the error here,e.g don't do anything or simply log it
}
}
If you don't rethrow the exception in the catch block, execution will fall off the end of the catch block and continue as if there was no exception.
If you mean you'd like to recall the method wether an Exception was thrown or not just place this in a while loop i.e:
Public static void main(Strings[] args)
{
boolean run=true;
while(run) {
try {
System.out.print("Hello,");
readsource();
throw new IOException();
if(1==2)run=false;//stop the loop for whatever condition
} catch(IOException ioe) {
ioe.printStackTrace();
}
System.out.println(" world!");
}
}
}
Private static void readsource() throws IOException
{
...
}