In the following piece of code :
import java.io.*;
import java.io.FileReader;
public class ExceptionPropagationDemo {
public static void main(String[] args){
ExceptionPropagationDemo testObject =new ExceptionPropagationDemo();
testObject.throwException1();
}
public void throwCheckedException(){
try{ //try - catch error block
BufferedReader br;
br = new BufferedReader(new FileReader("/Project1/src/employee.txt"));
} catch(FileNotFoundException e){
System.out.println("An IO exception happened and has been handled");
}
finally {
System.out.println("This block always executes.");
}
}
public void throwException2() {
throwCheckedException();
}
public void throwException1(){
throwException2();
}
}
I'm trying to catch a checked exception and handle it. In my case it would be FileNotFoundException, but I don't know for what reason it never runs the catch block which I'm trying to print a message or any other functionality, but it seems it jumps over.Thank you
Related
I have run the code of Client-Server interaction. Ignore the part of threading, I know that doesn't work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Client {
public static void main(final String[] args) throws Exception {
Socket socket = null;
while (true) {
try {
socket = new Socket("localhost", 3456);
System.out.println("Connect Ho gaya");
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader sr_receive = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Thread sendMes = new Thread(new Runnable() {
public void run() {
while (true) {
try {
String send = br.readLine();
pw.println(send);
} catch (Exception e) {
System.out.println("Send Message Problem");
}
}
}
});
Thread recMes = new Thread(new Runnable() {
public void run() {
while (true) {
try {
String recieve;
if ((recieve = sr_receive.readLine()) != null);
System.out.println("Server:" + recieve);
} catch (Exception e) {
System.out.println(e);
}
}
}
});
while (true) {
recMes.run();
sendMes.run();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
socket.close();
}
}
}
}
When I run this Client side program (without Server program running), I expect it to keep showing the exception until I run Server side program as it made it an infinite loop.
But on running it, initially it shows exception that it exits the program. And also when I remove the finally part it keeps showing the exception and an infinite loop.
Your finally block is throwing an exception. When this happens, execution exits the try-catch-finally-block, and the loop it's in.
The exception is probably caused by socket being null. This would happen if opening the connection in the Socket(host,port) constructor fails, and an exception is thrown without anything being assigned to socket. Adding an if-statement to check for this in the finally block would help.
It's also possible that socket.close is throwing an IOException. You would need to add another try-catch for that.
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ioe) {
e.printStackTrace();
}
}
}
I want to convert my IO Class from java on Eclipse to the Android API. For some reason it's not working on android!It is giving me a NullPointerException on my Println method. This class is used to create, write, read and open textfiles. My goal is to make all these methods readable on android.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
public class IO {
private static PrintWriter fileOut;
private static BufferedReader fileIn;
public static void createOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
} catch (IOException e) {
System.out.println("*** Cannot create file: " + fileName + " ***");
}
}
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void openOutputFile2(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
} catch (IOException e) {
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
public static void print(String text) {
fileOut.print(text);
}
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
public static void closeOutputFile() {
fileOut.close();
}
public static void openInputFile(String fileName) {
try {
fileIn = new BufferedReader(new FileReader(fileName));
//System.out.println("opening " + fileName);
} catch (FileNotFoundException e) {
System.out.println("***Cannot open " + fileName + "***");
}
}
public static String readLine()
// throws IOException
// Note: if there's an error in this method it will return IOException
{
try {
return fileIn.readLine();
} catch (IOException e) {
e.printStackTrace();
return "errors";
}
}
public static void closeInputFile() {// throws IOException
// Note: if there's an error in this method it will return IOException
try {
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you're getting a NullPointerException in println then that would be because 'fileOut' is null.
public static void println(String text) {
fileOut.println(text);
//System.out.println(text);
}
You're actually reacting on your second error because you've ignored the first one. In all cases where you set fileOut you're swallowing (effectively hiding) the error. E.g.
public static void openOutputFile(String fileName) {
try {
fileOut = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)));
} catch (IOException e) {
//Don't do this, it makes debugging much more difficult.
//Because the root problem is hidden.
//So now you have 2 problems to solve.
//And you've thrown away the information that might have
//helped to solve the problem in the first place.
System.out.println("*** Cannot open file: " + fileName + " ***");
}
}
Stop hiding errors, if something goes wrong you need to find out about it. Because invariably, ignoring errors results in more complex errors later down the line.
Fix you bad exception handling, and you'll be able to track down the root problem (probably file not found or a permission error).
I work in BlueJ in Windows. I tried to read a character in Java using the following method:
import java.util.Scanner;
import java.io.*;
public class Test{
public static void main(String args[]) {
InputStreamReader instream = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
}
}
When I compiled it, the compiler gave an error:
Unreported exception java.io.IOException; must be caught or declared
I did not understand the problem. Can anyone suggest me a way to do it properly.
The line stdin.read() could throw an IOException which is what the error message is telling you. You need to handle this by either declaring that your main method will throw it:
public static void main(String args[]) throws IOException {
// ...
}
or by handling the IOException inside main by using a try/catch like this:
public static void main(String args[]) {
try {
InputStreamReader instream = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
} catch (IOException ex) {
// handle error in some way
ex.printStackTrace();
}
}
Use try catch block to handle IOException in your code. you can do this.
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main(String args[]) {
try {
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
} catch (IOException ex) {
System.out.println("Error : " + ex.getMessage());
}
}
}
Catch the exception.
public static void main(String args[]) {
try{
InputStreamReader instream = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader(instream);
char c = (char) stdin.read();
}catch(IOException ioe){
ioe.printStackTrace();
// write your handling
}catch(Exception err){
err.printStackTrace();
}
}
// You can catch relevant multiple exceptions using catch block. If you are not sure of specific exception, catch generic Exception. All sub classes of Exception should be handled first and generic Exception should be caught in the last.
i currently have this code
My problem is that when i give a number 1 or 2, it doesn't give it and just says 'Not valid input'.
It would be nice if anyone could explain me why is it happening.
Thanks for any answer.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Screen {
private static BufferedReader stdin;
private static PrintStream os;
public static void main(String[] args) throws IOException{
try {
stdin = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
System.exit(1);
}
try {
switch (Integer.parseInt(selectAction())) {
case 1:
os.println("1");
System.err.print("Hello World ");
break;
case 2:
os.println("2");
System.err.print("Another Word ");
break;
}
} catch (Exception e) {
System.err.println("not valid input");
}
}
public static String selectAction() throws IOException {
System.out.println("1. Hello World.");
System.out.println("2. Another Word.");
System.out.print("\nMake selection: ");
return stdin.readLine();
}
}
Provide an initialization for os to prevent the NullPointerException. Your code works if I change the os declaration like
private static PrintStream os = System.out;
Also, please don't swallow the Exception
} catch (Exception e) {
System.err.println("not valid input: " + e.getMessage());
e.printStackTrace(System.err);
}
I have no idea why I get the message "cannot be resolved" on out in eclipse on the 11th line
import java.io.*;
public class driver {
public static void main(String[] args) {
try {
PrintWriter out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
OK so now I have this
import java.io.*;
public class driver {
public static void main(String[] args) {
PrintWriter out = null;
try {
out = new PrintWriter("output.txt");
}
catch (FileNotFoundException e) {
System.out.print("file not found");
e.printStackTrace();
}
out.print("hello");
out.close();
}
}
Why doesn't eclipse create a file once I close out?
Declare your PrintWriter before the try block so it's scope isn't limited to the try block.
You can also use new try-with-resource block introduced in JDK 1.7, in this advantage is you don't need to worry about closing any resource which implements Closable Interface.
Then code will look like this:
try (PrintWriter out = new PrintWriter("output.txt"))
{
out.print("hello");
}
catch (FileNotFoundException e)
{
System.out.print("file not found");
e.printStackTrace();
}