It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This question was asked to me on an interview. In the below snippet the exception occur in the third line of the try block. The question was how to make the 4th line execute. The third line should be in the catch block itself. They gave me an hint 'using throw and throws'.
public void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
out.toString();
System.out.println("Stop");
}catch(NullPointerException e){
System.out.println("Exception");
}
}
Can any one help. Thanks in advance.
First, the exception happens on the third line of the try block - at the out.toString(), not the 2nd line.
And I am assuming you want the fourth line to execute (ie. printing stop)
There are different ways to make the next line (printing stop) to execute, if you want to simply make the Stop is printed:
public static void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
out.toString();
System.out.println("Stop");
}catch(NullPointerException e){
System.out.println("Stop");
System.out.println("Exception");
}
}
or given the hint that
the third line should be in the catch block itself
public static void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
Exception e = null;
try
{
out.toString();
}
catch(Exception ex)
{
e = ex;
}
System.out.println("Stop");
if(e != null)
throw e;
}catch(Exception e){
System.out.println("Exception");
}
}
There are other ways to do this, eg. finally block, etc. But with the limited amount of information given and with the goal of making it work - the above should suffice.
You could do this:
public void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
out.toString();
}catch(NullPointerException e){
System.out.println("Exception");
} finally {
System.out.println("Stop");
}
}
Thorny snippet, the question was :
what's happen when you crash an internal address, here
out output, is replaced with String but it is null,
or
is it possible to print a null String, with a snippet around to focuse your attention.
you can rewrite the line : ("" + out).toString(); to pass to forth one.
'As is' it is not a technical interview, unless you have to push a second question about you have to do with the third line.
Test was : what the candidate does when he not see all parts of a problem, or when a problem is nested, is it able to ask help to understand the real problem.
EDIT after comment
Unless you comment the line, you have to capture the corrupted code :
try {
// Corrupted code to avoid
String out = null;
out.toString();
} catch (Exception e) {
// Careful (and professionnal) signal
System.out.println("out.toString() : code to repair.");
}
System.out.println("Stop"); // will appear to console
Related
I want to find out the error line number using try and catch. I tried to get some information from How to get error line number of code using try-catch, but it didn't help since I use different language.
Now, I am getting java.lang.NumberFormatException: For input string: "" when I do
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
}
I tried printing e.getStackTrace()[0].getLineNumber()); as well, but it seems like it's not showing the correct error line number. Is there any way I can get it easily? I have a pretty big file and I don't think I'll be able to go over line by line to figure out what's wrong.
Thanks!
If you use a Logger library, it can print the stack trace in debug mode that points to the line number. else printStackTrace() is your friend.
try {
// My Code Here
} catch(Exception e) {
System.out.println(e);
e.printStackTrace(); // This will give line number
}
package com.ms.common;
public class Run {
public static void main(String[] args) {
try {
int value = 5;
int divider = 0;
int result = value / divider;
} catch (Exception e) {
System.out.println(e.getStackTrace()[0]);
}
}
}
Error at Run.java at line# 11
com.ms.common.Run.main(Run.java:11)
This question already has answers here:
Returning from a finally block in Java
(6 answers)
Closed 7 years ago.
Look at the code below. Although the catch clause itself throws an exception, the finally block's return statement causes that exception to be swallowed. This method will return 420 even if something goes wrong in the catch block.
private static int foo() throws Exception
{
try {
throw new Exception("try");
} catch (Exception ex) {
throw new Exception("catch");
} finally {
String s = "";
return 420;
}
}
You should return something else if you encounters an Exception. The exception is only dangerous if the variable that threw that exception is used in the final return statement. Consider this:
int a;
try{
//...
}catch(Exception e){
//a throws an exception somehow
}finally{
returns a;
}
And when you use a on the other side like this:
a += 1;
You get a dangerous exception.
My suggestion is to do this:
try{
//...
}catch(Exception e){
//a throws an exception somehow
returns -1;
}finally{
returns a;
}
And on the other side:
if(return_value == -1) // skip or do something else;
This way, you won't get a unpredicted exception on the other side.
Return in finally is a very bad idea. It doesn't hide only the exceptions you throw yourself, but also virtual machine errors such as stack overflow or out of memory errors. These errors can be thrown at any point, including when the key invariants of data structures don't hold, and it will be impossible to predict what the program will do.
In your case it is safe, but if we change your scenario a little
private static FileReader foo() throws Exception{
try {
throw new Exception("try");
} catch (Exception ex) {
throw new Exception("catch");
} finally {
return new FileReader("");//this may also throw something
}
}
Now, because we didn't specify proper path in your file system return new FileReader(""); will throw FileNotFoundException and we will lose exception thrown in catch section with new Exception("catch"); which is potentially dangerous.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Well I have this problem and I dont know whats wrong with the codeing,
catch (FilenotFoundException e){
system.out.println("File not found");
}
try
{
FileReader freader = new FileReader("MyFile.txt");
}
}
Its asking for what the error is?? I thought it may be the e not being capitalized is that the reason?
A try{} block should be followed by a catch{} block or finally{} block, you have reversed it.
Use like this: -
try {
FileReader freader = new FileReader("MyFile.txt");
} catch (FileNotFoundException e){
System.out.println("File not found");
}
As per Java Naming Convention: -
Class Names start with a capital letter, and all subsequent word also start with capital letter. So, FilenotFoundException should be FileNotFoundException
And, system should be -> System.
A catch{} block follows a try{} block, not the other way around.
Also, FilenotFoundException should be FileNotFoundException. I doubt it will compile with the alternate spelling. Likewise with system vs. System, as indicated in #Rohit Jain's answer.
It should be otherway. try followed by catch.
try
{
FileReader freader = new FileReader("MyFile.txt");
}catch (FileNotFoundException e){
System.out.println("File not found");
}
Since Java 7:
try( FileReader freader = new FileReader("MyFile.txt"))
{
use freader
}// try
catch( IOException e)
{
e.printStackTrace();
}
catch block should follow try
try {
//code that exception might occur
}
catch(Exception ex) {
//catch the exception here.
}
your try block should either be followed by catch or finally.
try {
//code that exception might occur
}
finally {
//close your resources here
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am new to socket programming, and have a piece of code which opens a socket and writes into it. I set the timeout for the socket as one minute, and want to close the socket and exit after I reach a certain condition.
My code is not closing the socket when the condition is met:
#Override
public void run() {
Socket socket =null;
PrintWriter writer = null;
BufferedReader reader = null;
String host = ServiceProperties.getInstance().getControllerHost();
String port = "1234;
String info="";
// TODO Auto-generated method stub
try {
socket = new Socket(host, Integer.valueOf(port));
socket.setSoTimeout(60000);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
SampleBean sBean = (SampleBean) (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sampleBean"));
info = ControllerDAO.getInstance().getControllerAndTimeScheduleInfo(sBean.getId());
writer.println("set TimeSchedule "+ info +" value ["+str+"]");
}
catch(UnknownHostException ex) {
ex.printStackTrace();
}
catch(IOException ex) {
ex.printStackTrace();
}
String line="";
try {
System.out.println("BEFORE WHILE");
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
while((line= reader.readLine())!=null ) {
System.out.println(line);
if(line.contains("OK")){
System.out.println("line contains OK ");
break;
}
try {
Thread.sleep(5000);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("AFTER WHILE");
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
}
catch(IOException ex) {
ex.printStackTrace();
}
try {
writer.close();
reader.close();
socket.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
});
thread.run();
Output:
//"BEFORE WHILE"
// 14:54:55
// prints line
// //prints empty line
// now it waits for like 40 seconds
// line contains OK //condition met here
// breakoutof the loop
// "AFTER WHILE"
// 14:55:55
Why is it waiting on the third iteration? The third iteration is when the condition is met, after waiting for about 40 seconds.
What am I doing wrong?
You need to catch a SocketTimeoutException (see the doc) if your request times out and then close the socket in that catch, as the socket stays valid even if there is a time out.
There are a few problems here, but I think the main one is that you are not closing the socket properly. This should be in the finally block of the try block that encapsulates the sockets, NOT in its own try block.
SO_TIMEOUT does not affect close(), try setting SO_LINGER.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I followed the tutorial here: http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/
And have implemented the following code as an example:
File scoreFile = new File("score.txt");
if(!scoreFile.exists()) {
scoreFile.createNewFile();
}
oFile = new FileOutputStream(scoreFile, false);
oFile.write("Score = 1".getBytes());
oFile.flush();
oFile.close();
But nothing is being written to the file score.txt.
EDIT: The whole function is given below:
// Set win or loose to score.dat.
public void setScore(boolean won, boolean reset){
out.println("setScore()");
long timePassed = (timeEnd - timeStart)/1000; // Seconds passed.
double[] prevScore = getScore(); // get previous score (Won, Lost).
// Create a writer to edit the file.
File scoreFile = new File("score.txt");
if(!scoreFile.exists()) {
try {
scoreFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(!reset){
if(won){
// Add time to Win values.
prevScore[0] += timePassed;
}
else{
// Add time to Lost values.
prevScore[1] += timePassed;
}
try {
FileOutputStream oFile = new FileOutputStream(scoreFile, false);
// Write new score.
byte[] contentBytes = (String.valueOf(prevScore[0]+" "+prevScore[1])).getBytes();
oFile.write("Bye".getBytes());
oFile.flush();
oFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
// If battle ended, delete the scores.
FileOutputStream oFile;
try {
if(!scoreFile.exists()) {
scoreFile.createNewFile();
}
oFile = new FileOutputStream(scoreFile, false);
oFile.write("Error".getBytes());
oFile.flush();
oFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I know where the file is created because I can see that it creates the file, but it doesn't populate it with any text.
That piece of code works for me... Are you looking at the right place? You can try to change the filename to "C:\\score.txt" for example to make sure you look in the right folder.
The code definitely works.(assuming you've declared oFile) .Score.txt must be in your working directory