I am trying execute below code. But I am getting compile time errors. I have written below code to display the contents of the file "myfile.txt".
But Actually there is no file "myfile.txt". Then an exception "FileNotFound" should be thrown at run time. But the below programme is not compiled.
Why am i getting compile time errors?
code:
import java.io.*;
class rethrow {
public static void main(String args[]) {
rethrow rt = new rethrow();
try {
rt.m1();
} catch (FileNotFoundException FNFE) {
FNFE.printStackTrace();
}
}
void m1() {
try {
FileInputStream fin = new FileInputStream("myfile.txt");
System.out.println("file contents");
int ch;
while ((ch = fin.read()) != -1)
System.out.println((char) ch);
fin.close();
} catch (FileNotFoundException FNFE) {
FNFE.printStackTrace();
throw FNFE;
} catch (IOException IOE) {
IOE.printStackTrace();
}
}
}
---------------------------`---------------------------
OUT PUT:
rethrow.java:11: exception java.io.FileNotFoundException is never thrown in bod
y of corresponding try statement
catch(FileNotFoundException FNFE)
^
rethrow.java:30: unreported exception java.io.FileNotFoundException; must be ca
ught or declared to be thrown
throw FNFE;
^
2 errors
you have to add the throws clause in method m1:
void m1() throws FileNotFoundException {
otherwise you have a Unreachable catch block for FileNotFoundException in your main method and Unhandled exception type FileNotFoundException in your method m1.
catching the exception in m1 is not necessary with that change.
Declare your method as following
void m1() throws FileNotFoundException
{
try
{
FileInputStream fin=new FileInputStream("myfile.txt");
System.out.println("file contents");
int ch;
while((ch=fin.read())!= -1)
{
System.out.println((char)ch);
}
fin.close();
}
catch(FileNotFoundException FNFE)
{
FNFE.printStackTrace();
throw FNFE;
}
catch(IOException IOE)
{
IOE.printStackTrace();
}
}
You should declare what type of exceptions your method throws to the calling method.
Related
I'm practicing with try-with-resources for my methods to understand that.
This is my example method.
public void a(File f) throws FileNotFoundException, IOException {
try (FileInputStream fis = new FileInputStream(f)) { // suppose FileNotFoundException occurs here
byte[] buffer = new byte[7];
fis.read(buffer); // suppose IOException occurs here
}
}
Now suppose that an exception occurs as FileNotFoundException for the new FileInputStream() and a IOException on the fis.read().
this is the use of my method in another class.
try {
a(new File(""));
} catch (IOException ex) {
ex.printStackTrace();
Throwable[] suppressedExceptions = ex.getSuppressed();
if (suppressedExceptions.length > 0)
for (Throwable exception : suppressedExceptions)
System.err.println(exception.toString());
}
As in the previous code. Should I use the getSuppressed() method always when I use try-with-resources?
And when, where and how should I use addSuppressed() method?
I am trying to run the below code but getting compilaton error as "Unhandled exception type FileNotFoundException", as per my understanding this should not happen since try catch and finally blocks are added in the calling method.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test
{
public static void main(String[] args)
{
myMethod();
}
public static void myMethod() throws FileNotFoundException
{
try
{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e)
{
System.out.println("in the catch block");
throw e;
}
finally
{
System.out.println("in the finally block");
}
}
}
Remove throws FileNotFoundException from the myMethod signature (and then you'll need to remove throw e; from the catch block).
Or, add a try and catch to your main method (to handle the FileNotFoundException that you have indicated myMethod can throw).
Or, add throws FileNotFoundException to the signature of main (as pointed out by Andreas in the comments).
In short, the compiler will not allow you to have a code path with checked exceptions that are not handled.
In the catch block, you are throwing the Exception again once you catch it. If you really want to throw it from the myMethod() even after catch it, just add another try-catch to the main method.
public static void main(String[] args){
try{
myMethod();
}catch(FileNotFoundException e){
System.out.println("catch block in main");
}
}
Or else if you want to just catch the Exception in your myMethod(), don't throw it back.
try{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e){
System.out.println("in the catch block");
}
finally{
System.out.println("in the finally block");
}
you can read more about re-throwing exceptions in following question.
Rethrow exception in java
It's been a while since I've used Java so I feel silly that this is confusing me, but I have a class 'FileProcessor' in a 'FileProcessor.java' file. I'm trying to use it in my 'Driver.java' file but I keep getting this error:
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
I'm a little confused by the whole exceptions thing in Java and I thought I handled it in my FileProcessor.java file but I don't know.
FileProcessor.java
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
public class FileProcessor{
/**
* Reads one line from file
* #param arg A file
* #return The line that is read
*/
public String readLineFromFile(File f) throws FileNotFoundException,
IOException{
BufferedReader br = null;
String line;
try{
br = new BufferedReader(new FileReader(f));
line = br.readLine();
return line;
}
catch(IOException e){
e.printStackTrace();
System.err.println("Read method failed");
throw new IOException();
}
catch(FileNotFoundException e1){
e1.getMessage();
System.err.println("File is not found");
throw new FileNotFoundException();
}
}
}
Driver.java
import java.io.File;
import java.io.FileNotFoundException;
public class Driver{
public static void main(String args[]){
File inFile = null;
if (0 < args.length){
inFile = new File(args[0]);
}
else{
System.err.println("No input file found");
System.exit(0);
}
FileProcessor fileProcessor = new FileProcessor();
String lineRead;
try{
lineRead = fileProcessor.readLineFromFile(inFile);
}
catch(FileNotFoundException e){
throw new FileNotFoundException();
}
}
}
Your main throws a new FileNotFoundException in the catch block which can't be catched outside of main. Change:
import java.io.File;
import java.io.FileNotFoundException;
public class Driver{
public static void main(String args[]){
File inFile = null;
if (0 < args.length){
inFile = new File(args[0]);
}
else{
System.err.println("No input file found");
System.exit(0);
}
FileProcessor fileProcessor = new FileProcessor();
String lineRead;
try{
lineRead = fileProcessor.readLineFromFile(inFile);
}
catch(FileNotFoundException e){
System.out.print(e.getMessage());
}
}
}
Throwing a new IO- or FileNotFoundException when you catch them is not a good handling of this exceptions.
catch(IOException e){
e.printStackTrace();
System.err.println("Read method failed");
throw new IOException();
}
First, you loose the Exception information (which file can not be found, what exactly happened, ...). Second, it does not really catch them if you throw it again, so you have to catch them again one frame above.
So, the simplest possible solution is to delete the throw statement.
public class FileProcessor{
public String readLineFromFile(File f)
// this can be deleted if you catch the exceptions
// in here (and do not rethrow them)
// throws FileNotFoundException, IOException
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(f));
return br.readLine();
} catch(IOException e) {
e.printStackTrace();
// throw new IOException();
}
// this can be deleted because FileNotFoundException is a
// subclass of IOException and is caught above
// catch(FileNotFoundException e1){
// e1.getMessage();
// System.err.println("File is not found");
// throw new FileNotFoundException();
// }
// and after all, you should close the BufferedReader
// or use the "try-with-resources"
finally {
if(br != null) { br.close(); }
}
}
}
There are few things to do with Exceptions.
You catch the Exception and you write your appropriate code needed to handle the Exception, Example logging, setting error message or triggering fail mail, retry with new file name etc. For this you write the catch block along with try.
2.You catch the Exception and you write your appropriate code needed to handle the Exception, Example logging etc but you want future code which calls your method to catch and process the exception again. In this case you will re throw the exception using throw new and add it in throws. you can even throw new Exception type like
catch(NullPointerException e) {
throw new RecipeNotFoundException("No recipe found");
}
Delay the handling to future code which calls this method. This is done by writing throws clause. Throws tell method(s) calling a method that there are possibilities an exception can occur here and it is not caught and you need to catch and you wont write catch.
In your code you have caught the code in FileProcessor.readLineFromFile(File) method but you have also added throws clause to the method. So the system thinks there are chances an exception can be re thrown and not caught possible another FileNotFoundException from the catch block.
One more thing after catching the Exception you have re thrown same exception throw new IOException(); and throw new FileNotFoundException(); remove that too.
If you go through Java documentation on FileNotFoundException and IOException here. docs.oracle.com/javase/7/docs/api/java/io/… and docs.oracle.com/javase/7/docs/api/java/io/IOException.html you will notice FileNotFoundException actually extends IOException so you do not have to actually catch FileNotFoundException.
I want to get error message using java when exception are generated.
now I have java code with following scenario:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e)
}
}
method second(){
try{
my code
}catch(Exception e){
throw new Exception("Exception generate in second method",e);
}
}
now when the first method execute then I get only "Exception generate in second method" message but there is some other message printed on console by java so how to get that console error message.
Note: I have already try with e.getMessage(); and e.printStackTrace();
Every exception has a cause that you can get with getCause(). You can go recursively down them until you get to the root cause. Here is your example with a utility that dumps the exception with all its causes like the console does.
private void first() {
try {
second();
} catch (Exception ex) {
Log.e("CATCH", getExceptionDump(ex));
}
}
private void second() {
try {
throw new UnsupportedOperationException("We don't do this.");
} catch (Exception ex) {
throw new RuntimeException("Exception in second()", ex);
}
}
private String getExceptionDump(Exception ex) {
StringBuilder result = new StringBuilder();
for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
if (result.length() > 0)
result.append("Caused by: ");
result.append(cause.getClass().getName());
result.append(": ");
result.append(cause.getMessage());
result.append("\n");
for (StackTraceElement element: cause.getStackTrace()) {
result.append("\tat ");
result.append(element.getMethodName());
result.append("(");
result.append(element.getFileName());
result.append(":");
result.append(element.getLineNumber());
result.append(")\n");
}
}
return result.toString();
}
The message in the Exception constructor argument is not printed in the exception detail.
You can simply use this code to print the message :
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e.getMessage())
}
}
Hope this solves your problem
Why you cannot use print stack trace ?
Because A throwable contains a snapshot of the execution stack of its thread at the time it was created. (see Throwable)
It implies that, if you want to print the stack trace you need to use the printStackTrace() method BUT in your second method !
method second(){
try {
my code
} catch(Exception e) {
e.printStackTrace();
throw new Exception("Exception generate in second method",e);
}
}
Or using a the tricky method setStackTrace and using the printStackTrace() in first
method second(){
try {
my code
} catch(Exception e) {
Exception ex = new Exception("Exception generate in second method",e);
ex.setStackTrace(e);
throw ex;
}
}
method first(){
try {
second();
} catch(Exception e) {
e.printStackTrace();
}
}
You can print the cause of the exception you get. Try this:
method first(){
try{
second();
}catch(Exception e){
System.out.println("Error:> "+e);
if (e.getCause() != null) {
System.out.println("Cause:> " + e.getCause());
}
}
}
I believe this is the console message you want to achieve:
Error:> java.lang.Exception: Exception generate in second method
Try this code, when the catch block of the second method throws an exception the second method should declare it as throws or put a nested try catch within the catch block.
The exception is propagated to the first() method which is handled by its catch block.
public class Test {
public void first() {
try {
second();
} catch (Exception e) {
System.out.println("Error:> " + e);
}
}
public void second() throws Exception {
try {
throw new Exception();
} catch (Exception e) {
throw new Exception("Exception generate in second method", e);
}
}
public static void main(String ars[]) {
Test test = new Test();
test.first();
}
}
I'm trying to read ObjectOutputStream from a file and convert it to an arraylist.
This whole thing is happening inside a method which should read the file and return the array list:
public static List<Building> readFromDatabase(){
String fileName="database.txt";
FileInputStream fileIStream=null;
ObjectInputStream in=null;
List<Building> buildingsArr=null;
try
{
fileIStream = new FileInputStream(fileName);
in = new ObjectInputStream(fileIStream);
buildingsArr=(ArrayList<Building>)in.readObject();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
return buildingsArr;
}
}
Java tells me that this is dangerous.
What are the alternatives?
I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block.
I need to both make sure files will be closed, and return the array list I created as well.
Any ideas?
I can't put the return in the "try" block because it won't do it / it
won't close files in the "finally" block.
Wrong, finally block would still execute if you put return in try block. Thus you can return in your try block.
try
{
//your code
return buildingsArr;
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
}
I would suggest starting to use Java 7, and the try with resources clause. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ex:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
You must either throw an Exception or return a value:
All you need to prove this is comment out the return "File Not Found" after the finally block and see that it won't compile.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReturnFinallyExample
{
public static void main(final String[] args)
{
returnFinally();
}
private static String returnFinally()
{
try
{
final File f = new File("that_does_not_exist!");
final FileInputStream fis = new FileInputStream(f);
return "File Found!";
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally!");
}
return "File Not Found!";
}
}
You must have the return after the finally or you have to either:
declare the method to throws FileNotFoundExceptoin and re-throw the FileNotException out.
or
wrap the FileNotFoundException with throw new RuntimeException(e)