When trying to write read an int from standard in I'm getting a compile error.
System.out.println("Hello Calculator : \n");
int a=System.in.read();
The program throws an exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException at SamplePackege.MainClass.main(MainClass.java:15)
How do I fix this error?
My Code :
try {
Scanner sc = new Scanner(System.in);
int a=sc.nextInt();
} catch (Exception e) {
// TODO: handle exception
}
in.read() can throw a checked exception of type IOException.
You can read about Exception Handling in Java Here.
You can either change your program to throw an IOException, or you can put the read in a try catch block.
try{
int a=System.in.read();
catch(IOException ioe){
ioe.printStackTrace();
}
or
public static void main(String[] args) throws IOException {
System.out.println("Hello Calculator : \n");
int a=System.in.read();
}
The program doesn't have a bug.
The method read() requires you to catch an Exception in case something goes wrong.
Enclose the method inside a try/catchstatement:
try {
int a = System.in.read();
...
}
catch (Exception e) {
e.printStackTrace();
}
In any case I strongly suggest you to use documentation and/or Java tutorials, in which these things are clearly stated. Programming with out using them is just pointless. You will save yourself a lot of headaches, and probably also our time.
Related
I just started learning Java, and I am stuck. I was told to handle a call to a method, in the main method that can throw different types of exceptions.
What is thrown: IOException
How to handle: Wrap in an IllegalArgumentException with a message "Resource error" and throw it
What is thrown: FileNotFoundException
How to handle: Wrap in an IllegalArgumentException with a message "Resource is missing" and throw it:
This is a starting point, that is given:
static Exception exception = new FileNotFoundException();
public static void main(String[] args) throws Exception {
riskyMethod();
}
public static void riskyMethod() throws Exception {
throw exception;
}
To handle the exceptions riskyMethod() can throw, put it into a try-catch block. You can put several catch blocks after try to handle different exceptions. To wrap any exception into an IllegalArgumentException pass the exception as the second argument to the constructor. The first argument is the error string.
The whole code:
static Exception exception = new FileNotFoundException();
public static void main(String[] args) throws Exception {
try{
riskyMethod();
}catch(FileNotFoundException e){
throw new IllegalArgumentException("Resource is missing", e);
}catch(IOException e){
throw new IllegalArgumentException("Resource error", e);
}
}
public static void riskyMethod() throws Exception {
throw exception;
}
I did not test this code, but after adding the necessary imports it should work.
First, remove throws Exception from your main.
Handling an exception means not re-throwing it, or throwing a different one.
Catch the exception and do something with it:
public static void main(String[] args) {
try {
riskyMethod();
} catch (IOException e) {
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
You can print what you like - this is just a suggestion.
Note that you don't need to specifically catch FileNotFoundException, because it is an IOException.
In Java 7 Rethrow Exception feature added.I know it's concept but I want to see the real application of it and why this feature needed?
I will take examples from here
This is the example:
static class FirstException extends Exception { }
static class SecondException extends Exception { }
public void rethrowException(String exceptionName) throws FirstException, SecondException {
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
} catch (FirstException e) {
throw e;
}catch (SecondException e) {
throw e;
}
}
This compiles with both java 6 an 7.
If you want to keep checked exceptions from method signature, you have to keep cumbersome catch clauses in java 6.
In Java 7 you can do it in following way:
public void rethrowException(String exceptionName) throws FirstException, SecondException {
try {
if (exceptionName.equals("First")) {
throw new FirstException();
} else {
throw new SecondException();
}
} catch (Exception e) {
throw e;
}
So your benefit is that you have less cumbersome catch clause.
Use Rethrowing Exceptions with More Inclusive Type Checking feature
in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration
When you want to declare specific exceptions that can be thrown (mainly when you are catching a generic error)
For example see Precise Rethrow example:
public static void precise() throws ParseException, IOException{
try {
new SimpleDateFormat("yyyyMMdd").parse("foo");
new FileReader("file.txt").read();
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
throw e;
}
}
This also make your code compliant to Sonar's Raw Exception rule.
Note you can similarly catch Throwable
Couple of use-cases:
Using rethrow, you can edit the stacktrace information to make
it more accurate. Also when needed you can hide or rid off the
unnecessary internal details in stack trace.
try { //... }
catch (Exception e) { throw (Exception) e.fillInStackTrace(); }
Real application of fillInStackTrace is very well explained here:
Why is Throwable.fillInStackTrace() method public? Why would someone use it?
Quote from the book "Thinking in Java" written by Bruce Eckel:
If you want to install new stack trace information, you can do so by
calling fillInStackTrace( ), which returns a Throwable object that it
creates by stuffing the current stack information into the old
exception object
Add custom message to the thrown exception. Add custom message to thrown exception while maintaining stack trace in Java
A simple example I can think of:
void fileOperator(String operationType) throws Exception(){ ... }
void fileReader() throws Exception {
try{
fileOperator('r');
}
catch(Exception e){
throw Exception("Failed to read the file", e);
}
}
void fileWriter() throws Exception{
try{
fileOperator('w');
}
catch(Exception e){
throw Exception("Failed to write the file", e);
}
}
Also, we can throw a more specific exception type (say FileReadException, FileWriteException) from the catch block.
class TestExceptions {
public static void main(String[] args) throws Exception {
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
throw new RuntimeException();
} finally {
System.out.println("finally");
}
}
}
Following are the outputs when I try to run the code in eclipse multiple times. I believed so far that whenever the last line of the code from either try/catch block is about to be executed (which could be return or throws new Exception() type of stmt), finally block will be executed, but here the output different every time? Can anyone clarify if my assumption is right or wrong?
try
catch
Exception in thread "main" finally
java.lang.RuntimeException
at TestExceptions.main(TestExceptions.java:9)
Exception in thread "main" try
catch
java.lang.RuntimeException
at TestExceptions.main(TestExceptions.java:9)
finally
This is clearly because eclipse is printing the error stream and output stream without proper synchronization in console. Lot of people have seen issues because of this.
Execute the program in a command prompt and you will see proper output every time.
while agreeing with #Codebender, you can replace all the thows exception and replace them with printStackTrace(); then the exceptions and out will be printed in syn.
EG:
public static void main(String[] args) throws Exception {
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
e.printStackTrace();
} finally {
System.out.println("finally");
}
}
}
I have this method that throws exception
public String Pipeit() throws TransformerException,
TransformerConfigurationException,SAXException, IOException
i tried calling this method from a GUI
Pipe P = new Pipe (fname,x1name,x2name,x3name,oname);
view.setText(P.Pipeit()throws TransformerConfigurationException,SAXException,
IOException))
It kept giving this error
')' is expected.
throws TransformerConfigurationException,SAXException, IOException
should only be specified when you declare the method, not when you call it.
Also, variable names should by convention begin with a lower-case letter, and as #ssloan points out, method names should be in lower camelCase.
Change your code to
Pipe p = new Pipe (fname,x1name,x2name,x3name,oname);
view.setText(p.pipeIt());
Here's one way to write this with correct syntax:
Pipe P = new Pipe (fname,x1name,x2name,x3name,oname);
try {
view.setText(P.Pipeit());
} catch (TransformerConfigurationException e) {
//log/handle the exception
} catch (TransformerException e) {
//log/handle the exception
} catch (SAXException e) {
//log/handle the exception
} catch (IOException e) {
//log/handle the exception
}
While invoking method, you don't need to include entire method signature ( in this case throws clause).
view.setText(P.Pipeit()throws TransformerConfigurationException,SAXException,
IOException))
should be
view.setText(new P().Pipeit())
In Java, if a general exception is caught and rethrown, will outer methods still be able to catch specific exceptions?
In other words, can I do this:
try {
try {
//...
} catch (Exception e) {
//...
throw e;
}
} catch (SpecificException e) {
//...
}
re-throwing an exception does not change anything about it (it's still the same object originally thrown).
While jtahlborn answer is correct, there is one more appreciation: the compiler will see that you are throwing an exception of the generic type (even if at runtime it can be only of the specific class) and will force you to declare the generic exception in the method header.
private void test() throws FileNotFoundException {
try {
throw new FileNotFoundException("Es una exception");
} catch (IOException e) {
throw e; <-- Error because the method only throws
FileNotFoundException, not IOException
}
}
e is indeed FileNotFoundException, but as it is declared as IOException the compiler works with the broader class. What you can do is "cast" the exception.
throw (FileNotFoundException) e;
Eclipse marks the "throw e" in the inner catch as an unhandled exception, BUT it does catch the exception because when I run this it prints "It worked!". Thanks #jtahlborn. Unfortunately this means that there will still need to be an unnecessary try/catch block somewhere.
public class Tester {
public static void main(String[] args) {
try {
try {
throw new SpecificException("Test!");
} catch (Exception e) {
throw e;
}
} catch (SpecificException e) {
System.out.println("It worked!");
}
}
}