I'm learning chapter 5 of SCJP 6 Study Guide Exam_310-065 and in section Exception Declaration and the Public Interface it says
"Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown
exception."
How do we list each unhandled checked exception as a thrown exception and how does it look like in the code? Thanks.
It looks like this:
public void foo() throws SomeCheckedException, AnotherCheckedException
{
// This method would declare it in *its* throws clause
methodWhichThrowsSomeCheckedException();
if (someCondition)
{
// This time we're throwing the exception directly
throw new AnotherCheckedException();
}
}
See section 8.4.6 in the JLS for more information.
For instance, if you have:
public void doSomething() throws SomeException {
...
throw new SomeException();
}
And you want to invoke doSomething, you've got to either catch the exception, or declare the method using it as also susceptible of throwing SomeException, therefore propagating it further in the call stack:
public void doSomethingElse() throws SomeException {
doSomething();
}
Or
public void doSomethingElse() {
try {
doSomething();
}
catch (SomeException) {
// Error handling
}
}
Take into account that RuntimeExceptions are not checked exceptions, so they are an exception to this rule.
Related
This question already has answers here:
Rethrowing an Exception: Why does the method compile without a throws clause?
(5 answers)
Closed 6 years ago.
I came across a weird scenario in java today while coding around. I have a try..catch block in my method which does not have any throws clause and I am able to throw the exception object caught in the catch block. It is an object of the Exception class, hence it is not an unchecked exception. Also, It is not printing the stacktrace if exception arises instead the exception is just getting swallowed.
Below is my code example,
public class ExceptionTest {
public void test() {
try
{
// Some code which may throw exception.
}
catch(Exception ex)
{
// Compiler should ask me to have a *throws Exception* in the signature, when I am throwing an exception object.
throw ex;
}
}
}
However, if I am throwing a new exception object instead of the caught exception object, compiler is asking me to have a throws clause in the method signature.
N.B: I am facing this situation when running in Java 7 or 8.
I am wondering, where is the thrown object going to? Anyone with any idea on this please...
You'll see this if the code in the try block can't throw any checked exception. At that point, the compiler knows that the only kind of exception caught by the catch block has to be an unchecked exception, and so it can therefore be rethrown. Note that if you assigned a different value to ex within the catch block, the compiler would no longer be able to have that assurance. At the moment, ex is effectively final.
If you try to call something that is declared to throw a checked exception within the try block, the code will fail to compile as expected.
For example:
public class ExceptionTest {
public void test() {
try {
foo();
} catch(Exception ex) {
throw ex;
}
}
public void foo() throws java.io.IOException {
}
}
Gives an error of:
ExceptionTest.java:12: error: unreported exception IOException; must be caught or declared to be thrown
throw ex;
^
As for where the exception "goes" - if the code in the try block throws an unchecked exception, it gets propagated as normal. Try this:
public class ExceptionTest {
public static void main(String[] args) {
test();
}
public static void test() {
try {
String x = null;
x.length();
} catch(Exception ex) {
throw ex;
}
}
}
Running that gives the following output, as expected:
Exception in thread "main" java.lang.NullPointerException
at ExceptionTest.test(ExceptionTest.java:10)
at ExceptionTest.main(ExceptionTest.java:4)
JLS 11.2.2 documents what exceptions a statement can throw - your code will only compile if there are no checked exceptions that can be thrown.
please check that you are really throwing an exception in the code. Otherwise the compiler will not care about catching the exception.
public class ExceptionTest {
public void test() {
try
{
throw new Exception("Error");
}
catch(Exception ex)
{
// My Compiler says that I don't catch the exception
throw ex;
}
}
}
Compiler: Error:(14, 13) java: unreported exception java.lang.Exception; must be caught or declared to be thrown
I've created a custom Exception class that I want to use in my application:
public class MyException extends Exception {
private static final long serialVersionUID = -2151515147355511072L;
private String message = null;
public MyException() {
super();
}
public MyException(String message) {
super(message);
this.message = message;
}
public MyException(Throwable cause) {
super(cause);
}
#Override
public String toString() {
return message;
}
#Override
public String getMessage() {
return message;
}
}
But when I try to use this class, like below, it gives a compile time error.
try {
System.out.println("this");
} catch (MyException e) {
// TODO: handle exception
}
Compile time error:
Unreachable catch block for MyException . This exception is never thrown from the try statement body
My question is if I'm extending Exception class & calling super in all constructors, then why this error is occurring?
Obviously, you are not doing anything that'd generate a MyException. First write a method with the signature throws MyException, call it and then your problem is solved. Here is an example:
public void someMethod()throws MyException
{
//some condition here.
//if met..
throw new MyException("cause");
}
and modify your main code as:
try {
someMethod();
System.out.println("this");
} catch (MyException e) {
// TODO: handle exception
}
The exception you created is a checked exception and must be thrown from somewhere to catch it.
Any exception created by a java developer by extending Exception class is a checked exception. And the rules applicable for checked exception will be applied on such exceptions.
Another form of exception is called Unchecked Exception and usually created by extending RuntimeException Class. A developer is free to catch such exception without an explicit need for throwing it somewhere from your code.
class Exception is also not thrown generally. I just want MyException behave like Exception.
This is what being further asked in one of the comments:
My take on this is you can think Exception class as a large container which have many different and unique(to the point) child exceptions defined. And mostly these fine grained exceptions are thrown from Java Code. In a abstraction hierarchy, Exception is at higher level (not Highest as, Throwable is sitting there).
Further, as a developer we all are always interested into the finer details like what kind of Exception is thrown. However, while handling exception, we sometimes write
try{
//some code lets assume throws IOException
//Some code lets assume throws FileNotFoundException
}
catch (Exception ex) {
//common handling which doesn't care if its IOException or FileNotFoundException
}
You can not intervene in this exception hierarchy by just writing MyException extends Exception. By this what you are doing is your MyException is a type of Exception not itself Exception class. So, you can't replace Exception caught in catch with your MyException.
Can you try with:
try {
System.out.println("this");
throw new MyException();
} catch (MyException e) {
// TODO: handle exception
}
Your exception wasn't thrown anywhere in the code. (try extending RuntimeException as another option)
What the compile time error says is right "This exception is never thrown from the try statement body". You don't have anything which throws MyException
I trying to throw inner exception in another exception through java Throwable but IDE told my that you must surround it with try/cath, What should I do to avoid from this problem?
try
{
//Some code
}
catch (IOException e)
{
Throwable cause = new Throwable();
cause.initCause(e);
throw cause.getCause();
}
Change your method signature to this:
public void someMethod() throws IOException
{
//some code
}
Have a look at this site for some useful information on checked exceptions and a little on the difference between checked and unchecked exceptions
Declare IOException as a checked exception in your function's signature.
In trying to refactor some I code I attempted to throw the exception in the catch clause like so -
try {
....
}
catch(Exception exception){
.....
throw exception
}
However when I attempted to throw the exception on line "throw exception" the compiler complained with a message that I needed to surround my throw clause in a new try/catch like so -
try
{
....
}
catch (Exception exception)
{
.....
try
{
throw exception
}
catch (Exception e2)
{
...
}
}
Why does the compiler require this and what use does it provide ?
Thanks
The exception java.lang.Exception is a checked exception. This means that it must either be declared in the throws clause of the enclosing method or caught and handled withing the method body.
However, what you are doing in your "fixed" version is to catch the exception, rethrow it and then immediately catch it again. That doesn't make much sense.
Without seeing the real code, it is not clear what the real solution should be, but I expect that the problem is in the original try { ... } catch handler:
If possible, you should catch a more specific exception at that point, so that when you rethrow it, it is covered by the method's existing throws list.
Alternatively, you could wrap the exception in an unchecked exception and throw that instead.
As a last resort, you could change the signature of the method to include Exception in the throws list. But that's a really bad idea, because it just pushes the problem off to the caller ... and leaves the developer / reader in the position of not knowing what exceptions to expect.
In Java, there is a distinction between checked and unchecked exceptions. An unchecked exception can essentially be thrown at any place in code and, if it's not caught somewhere, it will propagate up to the entry point of your application and then stop the process (usually with an error message and stack trace). A checked exception is different: The compiler won't let you just let it propagate, you need to either surround any code which might throw a checked exception with try-catch blocks (and "throw exception" is the simplest case if exception is an instance of a checked exception class) or you must mark the method which contains the call to code that might throw a checked exception with a "throws" declaration. If the desired behaviour is to throw an unchecked exception, then you'll need to wrap the exception in a RuntimeException. If the desired behaviour is to keep the exception checked, then you'll need to add a throws declaration to your current method.
In your original code, nothing catches the thrown exception. I would imagine you either have to specify that your function throws an exception or have another try/catch block as the compiler suggests to catch it.
Instead of
public void yourFunction(){
try {
....
}
catch(Exception exception){
.....
throw exception
}
}
try
public void yourFunction() throws Exception{
try {
....
}
catch(Exception exception){
.....
throw exception
}
}
My guess is that your trying to throw an exception sub class that isn't declared by the method as an exception type it can throw.
The following example works
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws Exception{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
However this example will give an error.
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (Exception e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
Note in the second example I'm simply catching Exception not RuntimeException, it won't compile as I throw Exception which is an undeclared throws, even though I do declare RuntimeException.
Yes the exception is a RuntimeException but the compiler doesn't know that.
Just thought of a third working example to show you. This one also works because your throwing the same type as you declare. (note the only change is the catch block)
package test.example;
public class ExceptionTest {
public static void main(String[] args) throws RuntimeException{
try {
int value = 1/0;
} catch (RuntimeException e) {
System.out.println("woops the world is going to end");
throw e;
}
}
}
You need to understand the differences between all three of these answers
I've never used the "throws" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I've been using exceptions without problems without doing it, so, why is it needed if, in fact, it's needed?
Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.
Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.
Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.
Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.
If a method is declared with the throws keyword then any other method that wishes to call that method must either be prepared to catch it or declare that itself will throw an exception.
For instance if you want to pause the application you must call Thread.sleep(milliseconds);
But the declaration for this method says that it will throw an InterruptedException
Declaration:
public static void sleep(long millis) throws InterruptedException
So if you wish to call it for instance in your main method you must either catch it:
public static void main(String args[]) {
try {
Thread.sleep(1000);
} catch(InterruptedException ie) {
System.out.println("Opps!");
}
}
Or make the method also declare that it is throwing an exception:
public static void main(String args[]) throws InterruptedException {
Thread.sleep(1000);
}
It can happen, even with checked exceptions. And sometimes it can break logging.
Suppose a library method uses this trick to allow an implementation of Runnable that can throw IOException:
class SneakyThrowTask implements Runnable {
public void run() {
throwSneakily(new IOException());
}
private static RuntimeException throwSneakily(Throwable ex) {
return unsafeCastAndRethrow(ex);
}
#SuppressWarnings("unchecked")
private static <X extends Throwable>X unsafeCastAndRethrow(Throwable ex) throws X {
throw (X) ex;
}
}
And you call it like this:
public static void main(String[] args) {
try {
new SneakyThrowTask().run();
} catch (RuntimeException ex) {
LOGGER.log(ex);
}
}
The exception will never be logged. And because it's a checked exception you cannot write this:
public static void main(String[] args) {
try {
new SneakyThrowTask().run();
} catch (RuntimeException ex) {
LOGGER.log(ex);
} catch (IOException ex) {
LOGGER.log(ex); // Error: unreachable code
}
}
You need to declare checked exceptions that your method throws.
If you declare 'throws Exception' that pretty much covers most if not all checked exceptions
You can always throw an unchecked runtime exception and not have to declare.
Im pretty sure if you try to throw a checked exception, and haven't declared the method as throwing that type, the code wont even compile (checking now).
EDIT, right so if you try something simple like
public static void main(String[] args) {
throw new Exception("bad");
}
you get a compile error.
Specifically for your question, if you invoke a method that is declared to throw Exception(s) you must either try/catch the method invocation, or declare that your method throws the exceptions.
The throws key word is used to throw an exception to another method.
It eases the handle exception to the user. Because then all of the exceptions can be handled in a method which is used to run.
Mostly it is mainly a method, so that the user does not need to explore inside the method.
It also throws keyword force to the compiler to handle the exception which could be occurring.
If you were a API developer, when you write a code, you might see that an exception could occur, so you use the throws keyword to handle it when the method runs.
Java throws keyword,
Java throws keyword is used to declare an exception.
throws is followed by class.
Checked exception can be propagated with throws.
It provides information to the caller of the method about the exception.
throws example,
void m()throws ArithmeticException{
//method code
}