exception handling, creating log and continue the program in JAVA - java

I am designing a program in JAVA that captures results in about 10 iterations. At the end of these iterations all the results must be written into a log file.
If any exception occurs then it should be written on my text file and secondly the program must not stop, it must go on till the last iteration is completed...
That is to say - if some error occur on any part of any iteration the program must not stop here. The error must be mentioned within my results by the name of error and it must go on and update my log file.
My code till now is bit lengthy...used try-catch, the try block is doing my calculations and writing my text file, but I need if incase some exception occurs my program must not stop and that exception must be updated in my log file.

You're looking for the try-catch block. See, for example, this tutorial.

OutputStream os = ....;
PrintStream ps = new PrintStream(os);
while(notDone) {
try {
doStuff();
}
catch(Throwable t) {
t.printStackTrace(ps);
}
ps.print(results);
}

the case is, in this kind of a question, you should better provide us a sample code, then only we can identify the problem without any issue.
If you just need to view the error, then "e.printStackTrace" will help you. The "e" is an instance of class "Exception".
However, if you need to LOG, then "Logger" class will help you, with Exception class.For an example,
try {
f = location.createNewFile();
} catch (IOException ex) {
Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
}
To do all of these, it is better to surround your code with try catch block

Related

File.createNewFile(): How to handle "unreported exception" error?

I'm new to the world of programming. I am on my 6th class and we were tasked to create a new file using an instance of File. I'm getting an io exception when compiling. I searched online but I can't seem to find an explanation I can understand about the issue.
Please bear with me but my code is:
import java.io.File;
public class TestFile{
public static void main(String[] args) {
File myArchive = new File("MyDocument.txt");
boolean x = myArchive.createNewFile();
System.out.println(x);
}
}
As I understand createNewFile() will provide a true value if the file is created, but I keep getting the following message.
TestFile.java:5: error: unreported exception IOException; must be
caught or decl ared to be thrown
boolean x = myArchive.createNewFile();
^ 1 error
From what I gathered online, there's an exception that needs to be caught. The instructor didn't advise of how to handle an exception on the code or anything to do with the commands try or catch.
Thank you very much for you assistance. If I'm not complying with any of the forums' guidelines, please let me know, this is my first post and again I'm fairly new to programing.
In java you will get many Exceptions and you have to handle It using try..catch block.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Additionally you have to define boolean x outside the try block and should be initialized to some value (either true or false) .
Try this code:-
import java.io.File;
public class Main {
public static void main(String[] args) {
File myArchive = new File("MyDocument.txt");
boolean x = true;
try {
x = myArchive.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(x);
}
}
Output:-
true
Just an intro to try-catch and what's it for:
Some operations may generate an error, which may even not be a mistake of the programmer, but may happen due to unforeseen circumstances.
For example, you want create a file, but at this moment, the file destination may become absent (e.g., a usb stick is taken out), or the disc may be full, or it may be an impossible filename (provided by another user through the keyboard, containing "forbidden" characters), or permission may not be given (e.g. in Android, when your phone asks for permissions to write files, you may grant it, or you may refuse to grant it for security's sake).
For such cases, Java provides you with an opportunity to try the error-prone code, and then catch the error. If an error happens, you don't want your app to crash. You want it to continue continue working, so you may warn the user on the screen that the file operation failed, and provide alternative actions.
So, basically, you do the following
try{
// place a risky part of code here
// like, creating a file
} catch (Exception error)
{
// This part will be executed only if there is an error
// in this part, you can change the wrong file name
// or tell the user that the disc is not available
// just do something about the error.
// If an error does not occur, then this part will not be executed.
}
try {
boolean x = myArchive.createNewFile();
System.out.println(x);
} catch (IOException e) {
e.printStackTrace();
}
The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block

why not debug rather why exception handling

we specify the exception in try and catch.If we know what exception is gonna be generated why go for exception handling rather than just debug that part of the code?
According to Oracle definition of Exception
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
CONCLUSION:
If you put a try {} catch block you know will always trow an Exception, your code is wrong.
For example, this code compiles? YES, but is wrong
String s = "throwMe!";
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
}
CORRECT EXCEPTION USE
System.out.println("Enter a number");
String s = Scanner..... // user enters something
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
// TELL USER THERE IS A PROBLEM
}
// TELL USER IS A GENIUS
This will have 2 execution flows, the correct one (user is a genius) but in the moment the user enters a value disrupting the flow (Integer.parseInt(s);) the Exception is thrown...
No, exceptions refer to run-time conditions that we cannot foresee
For example, the divide-by-zero error happens due to user inputting wrong data.
So you catch with try-catch
try {
}
catch(ArithmeticException){
}
You don't have to do exception handling or debugging, you can do both and good exception handling helps you debug your code later on.
If nothing else a catch block should print the Stack Trace which gives you information regarding where things went wrong with your code and it's much better than failing silently and then manually debug your whole code to search for the problem.
There are many other advantages to using exceptions for error handling as well.
Try / catch blocks are for errors that you cannot foresee. Things like null pointers and divide by 0 errors don't need a try catch blocks. Those things are typically errors on the part of programmers and should be debugged by the programmers. But things like IOException or SQLException, where you are interfacing with some other system that could fail or give invalid input that the programmer cannot control, those things need a try / catch block.

Java - How to keep running on exception

This question seems pretty simple. How do I keep running my application on an exception.
For instance how would I go about doing this.
Server application tries to run on port 1234, but it's not available. Normally it would just crash. But how can I make it keep running and say; Would you like to try another port?
Or if we're trying to load a file which doesn't exists. How do I avoid the program from crashing, but just display a little message saying the it was unable to load the file.
How is this done?
Use a try catch block.
try{
//Where exception may happen
}catch(Exception e){//Exception type. Exception covers it all.
//Print error if you would like or do something else
}finally{//Finally is optional, as the code in here will run regardless of an exception.
}
//program continues
Most try-catch blocks do not have finally at the end. You will use finally if you need code to be run whether or not there was an exception. More information about the finally block
Here's an example where a catch would fail, but the finally does execute:
int number = 0;
try {
number = 1 / 0;
} catch (IndexOutOfBoundsException e) {
System.out.println("Nooooo!");
} finally {
System.out.println("What just happened?");
}
System.out.println(number);
This outputs:
What just happened?
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ...
The catch failed to execute because it only catches IndexOutOfBoundsExceptions and not ArithmeticExceptions, which is what you get when you try to divide by zero.
I was suffering from same problem but my case was the exception thrown from binary tree class which terminated the program and I wanted it to continue execution.So, your problem can be solved by below written code.
do{
try{
//get the value for port
//it may throw exception
}
catch(Exception e){
// handle exception
}
//ask for yes or no to continue
}while(choice);
Well, this will keep asking for port values as long as you want.Use loops to ask values for ports continuously.
Remember:You can add code after catch block but not in between try and catch block.

IText Constructor not Throwing Exception or Following Flow

I have a static method used to get the title from a PDF using the metadata via itext, which is used as a small part of a major Task.
I noticed an inexplicable path that I narrowed down to this section of code. Specifically, in the line where I instantiate a PdfReader, the process doesn't throw an exception or continue through to the print statement. In fact, it clears out all of my for loops up to the top level of my program and acts as if nothing has happened and my task completed.
try {
System.out.println("Entered method");
PdfReader myReader = new PdfReader(file.getAbsolutePath());
System.out.println("Reader instantiated"); //if no issues, prints to console
Map<String, String> info = myReader.getInfo();
System.out.println(info.get("Title"));
return info.get("Title");
} catch (IOException e) {
System.out.println("PdfReader throws exception"); //if issues, prints to console
e.printStackTrace();
}
Unless I'm mistaken, when this set of code is executed in my method, either "Reader Instantiated" or "PdfReader throws exception" is printed out to the console.
Neither happens. Instead, the process skips every if/for/while loop it is currently in and ends the task.
I'm wondering if someone can explain to me what is happening and how I should go about fixing it?
In the odd event this is searched for, yes, catching Throwable stops the thread from bailing out. I had never seen something like this before. The cause behind the problem was that a PDF was password-protected, so getInfo() failed.

Java - ignore exception and continue

For my Java application, I am creating an instance of a user information object and populating it with a service that I don't control the source for.
The code looks like this:
// username given as parameter
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (Exception e) {
// Whatever
}
If LDAPService.findUser() can't locate a user, it will throw a NullPointerException and grind the rest of my application to a stop. It's okay if the user information isn't populated, so I want to be able to continue without causing everything else to start throwing exceptions.
Is there a way to do this?
I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.
But I would have written it like this instead:
UserInfo ui = new UserInfo();
DirectoryUser du = null;
try {
du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
// It's fine if findUser throws a NPE
}
if (du != null) {
ui.setUserInfo(du.getUserInfo());
}
Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.
You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (NullPointerException npe) {
// Lulz # your NPE
Logger.log("No user info for " +username+ ", will find some way to cope");
}
You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.
try{
throw new Exception();
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println("Made it!");
However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
You are actually ignoring exception in your code. But I suggest you to reconsider.
Here is a quote from Coding Crimes: Ignoring Exceptions
For a start, the exception should be logged at the very least, not
just written out to the console. Also, in most cases, the exception
should be thrown back to the caller for them to deal with. If it
doesn't need to be thrown back to the caller, then the exception
should be handled. And some comments would be nice too.
The usual excuse for this type of code is "I didn't have time", but
there is a ripple effect when code is left in this state. Chances are
that most of this type of code will never get out in the final
production. Code reviews or static analysis tools should catch this
error pattern. But that's no excuse, all this does is add time to the
maintainance and debugging of the software.
Even if you are ignoring it I suggest you to use specific exception names instead of superclass name. ie., Use NullPointerException instead of Exception in your catch clause.
You can write a try - catch block around the line you want to have ignored.
Like in the example code of yours. If you just continue your code below the closing bracket of the catch block everythings fine.
LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..
Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

Categories

Resources