This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 6 months ago.
Can we use throws and try-catch in the same method?
public class Main
{
static void t() throws IllegalAccessException {
try{
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args){
t();
System.out.println("hello");
}
}
The error displayed is
Main.java:21: error: unreported exception IllegalAccessException; must be caught or declared to be thrown
t();
^
1 error
So I thought of modifying the code and I added an another throws statement to main() method and the rest is same.
public class Main
{static void t() throws IllegalAccessException {
try{
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e){
System.out.println(e);
}
}
public static void main(String[] args) throws IllegalAccessException{
t();
System.out.println("hello");
}
}
But now I'm getting the desired output.
But I have some questions...
Can we use throws and try-catch in single method?
In my case is it necessary to add two throws statement , if not tell me the appropriate place to add?
In your code
void t() throws IllegalAccessException
you are telling the compiler that this code throws an exception (whether it does or not is another matter), and so any method calling this method either has to catch it or declare that it also throws it etc. etc.
As you are not actually throwing an exception from t you can remove the declaration.
void t()
Related
If I add the throws keyword in the method signature and handle it in my main() inside my TestClass{}, is it a good approach or should I handle the exception in the method in which it occurs fooBar(), which approach is recommended or what are the trade-offs between the two. Sorry this question might seem a little weird, just a newbie in Java.
public class Foo {
//private fields
public Foo() {
//ctor
}
//accessors and mutators
//method that throws exception
public void fooBar() throws FooBarException {
throw new FooBarException();
}
}
Generally, the scope of try block should be as small as possible.
public void fooBar(){
try{
//Lines that can through error
}
catch (FileNotFoundException e) {
//Handle exception Here
//e.printStackTrace();
/*
other code that will not throw any error
*/
}
or if the whole block may throw the error then
public void fooBar() throws FooBarException {
}
//Handle in the exception where you calling the method
I don't think I understand the try-catch block and throws really.
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
When in Eclipse, there is an error hint about 'Unhandled exception type xxx', and if you run this, you will get an
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type Exception
But in Idea, there's no errors. It runs and throws the exception correctly.
In my opnion, the 'e' was not declared as a RuntimeException(althrough it is an RuntimeException), so the tt() method must be declared with throws. But actually it's not. Why?
This should answer your question:
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
If you use throws, you tell those who use your function, "My function may throw exceptions. You have to handle that."
You should get difference of throws and throw in this sentence.
If you use try-catch, you handle that exception.
1) You should add throws keyword like below
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() **throws Exception** {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
2) Handle exception where you use function
public class TestException {
public static void main(String[] args) {
try{
new TestException().tt();
}catch(Exception e){
System.out.println("Error handled");
}
}
public void tt() throws Exception {
try {
throw new RuntimeException();
}catch (Exception e) {
throw e;
}
}
}
In general if you catch an exception you handle it. Like this
public class TestException {
public static void main(String[] args) {
new TestException().tt();
}
public void tt() {
try {
throw new RuntimeException();
}catch (Exception e) {
System.out.println("Error caught! ")
}
}
}
or
public class TestException {
public static void main(String[] args) {
try {
new TestException().tt();
}catch(Exception e){
System.out.println("Error caught! ")
}
}
public void tt() throws RuntimeException {
throw new RuntimeException();
}
}
You can also throw other's exception
public class TestException {
public static void main(String[] args) {
try{
new TestException().a();
}catch(Exception e){
System.out.println("Error handled");
}
}
public void a() throws Exception {
b();
}
public void b() throws Exception {
c();
}
public void c() throws Exception {
throw new RuntimeException();
}
}
I think that you want to look into 'Checked Exceptions' and 'Unchecked Exceptions'.
Only Checked Exceptions need to be declared in a methods signature, and RuntimeException is an unchecked exception (though you can declare it if you like - it just isn't necessary to compile).
https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
The API for java Exception says:
"The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary"
https://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
The API for java RuntimeException says:
"RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary."
In my opnion, the 'e' was not declared as a RuntimeException(althrough it is an RuntimeException), so the tt() method must be declared with throws. But actually it's not. Why?
Let's consider what we know:
When using rethrow syntax, the existing exception object (e) is rethrown.
e is an object of class Exception, or one of its subtypes.
RuntimeException is a subtype of exception, and is not compiled time checked, so it's possible the re-thrown object is a non compile time checked object.
The compiler cannot see a place where the code definitely, or even possibly throws a compile checked exception, and so it makes sense that it does not force those semantics.
For example, if you change your catch to an IOException, the compiler will not allow you to do that without a line in the try which could possibly lead to an IOException.
If you added such a line, then the compiler would recognize that the throw would rethrow a compile time checked exception, and make you catch it again, or mark the function with the appropriate throws clause.
As for eclipse, your code compiles OK in mine with my JDK.
I would expect the following code to raise a compile-time error on throw t;, because main is not declared to throw Throwable, but it compiles successfully (in Java 1.7.0_45), and produces the output you would expect it to if that compile-time error was fixed.
public class Test {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
}
It also compiles if Throwable is changed to Exception.
This does not compile, as expected:
public class Test {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch(Throwable t) {
Throwable t2 = t;
System.out.println("Caught "+t2);
throw t2;
}
}
}
This compiles:
public class Test {
public static void main(String[] args) {
try {
throwsRuntimeException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
public static void throwsRuntimeException() {
throw new NullPointerException();
}
}
This does not:
public class Test {
public static void main(String[] args) {
try {
throwsCheckedException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
public static void throwsCheckedException() {
throw new java.io.IOException();
}
}
This compiles as well:
public class Test {
public static void main(String[] args) throws java.io.IOException {
try {
throwsIOException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
}
public static void throwsIOException() throws java.io.IOException {
throw new java.io.IOException();
}
}
A more complex example - the checked exception is caught by an outer catch block, instead of being declared to be thrown. This compiles:
public class Test {
public static void main(String[] args) {
try {
try {
throwsIOException();
} catch(Throwable t) {
System.out.println("Caught "+t);
throw t;
}
} catch(java.io.IOException e) {
System.out.println("Caught IOException (outer block)");
}
}
public static void throwsIOException() throws java.io.IOException {
throw new java.io.IOException();
}
}
So there seems to be a special case to allow rethrowing exceptions when the compiler can determine that the caught exception is always legal to re-throw. Is this correct? Where is this specified in the JLS? Are there any other obscure corner-cases like this?
This is covered by JLS 11.2.2 (emphasis mine):
A throw statement whose thrown expression is a final or effectively final exception parameter of a catch clause C can throw an exception class E iff:
E is an exception class that the try block of the try statement which declares C can throw; and
E is assignment compatible with any of C's catchable exception classes; and
(...)
In other words, E, the type referenced in the doc, is the type that can be thrown, not the type of the catch clause parameter that catches it (the catchable exception class). It just has to be assignment compatible to the catch clause parameter, but the parameter's type is not used in analysis.
This is why the go out of their way to say a final or effectively final exception parameter--if t in your example were reassigned, the analysis would go out the window.
Because the compiler is smart enough to know that a checked exception can not be thrown from the try block, and the caught Throwable is thus not a checked exception that must be declared.
Note that this is true since Java 7, if I'm not mistaken.
When you catch Throwable or Exception and the variable is effectively final you can rethrow the same variable and the compiler will know which checked exceptions you could have thrown in the try {} catch block.
I am currently writing a Text Editor using linked lists, and I am pretty much done but I come across a FileNotFoundException when trying to test my program's command line, even though I declared it to be thrown.
Here is the skeleton for my Editor:
public class Editor {
public Editor() {
}
public void commandLine() throws FileNotFoundException {
}
}
Here is the driver for my program:
public class EditorTest
{
public static void main(String[] args)
{
Editor asdf = new Editor();
asdf.commandLine();
}
}
I am still getting an error for an unreported FileNotFoundException even though I declared it to be thrown in my command line method. What is wrong?
You need to add throws FileNotFoundException to your main method. Or, you can add:
try {
asdf.commandLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
to your main method, depending on what you need to do based on that exception.
Yo need to declare it on main, too
public static void main(String[] args) throws FileNotFoundException {
Declaring an Exception to be thrown in a method (i. e. using throws MyException) doesn't prevent the exception to be thrown, it rather allows the method to throw it for a caller of that method to have to catch that Exception
Do we not need exception specification for the main method in a Java program. For example, the following code works exactly the same without specifying "throws Xcept" for the main method.
class Xcept extends Exception {
public Xcept(){
}
public Xcept(String msg){
super(msg);
}
}
public class MyException {
public void f() throws Xcept {
System.out.println("Exception from f()");
throw new Xcept("Simple Exception");
}
public static void main(String[] args) throws Xcept {
MyException sed = new MyException();
try {
sed.f();
} catch(Xcept e) {
e.printStackTrace();
}
finally {
System.out.println("Reached here");
}
}
}
I read that java enforces this, but I don't get a compile time error if I exclude this specification for the main method.
That's because Xcept will never be thrown out of your main method, as you actually catch it there... The sed.f() call may result in an Xcept being thrown, but it's caught and handled.