class Xyz {
public static void yolo() {
try {
throw new IllegalAccessException("demo");
} catch (IllegalAccessException e) {
System.out.println("lol");
}
}
public static void main(String args[]) {
Xyz.yolo();
}
}
Since there is no exception that is going out of the yolo method, I don't need to write "yolo() throws IllegalAccessException". Right?
You are correct. You only need to declare unhandled checked exceptions.
Exactly. A method only needs to declare throws for exceptions which leave it and aren't handled by itself.
Perfect!
If you will use throws keyword for handing Exception then this method will not handle the exception rather then main() will handle this exception at time of calling this method.
Related
Error message:This exception is never thrown from the try statement body.
Here shows a java program:
class err1 extends Exception {}
class Obj1 {
Obj1() throws err1 {
throw new err1();
}
}
class Main {
public static void main(String[]argv) {
Class a[] = {Obj1.class};
try {
a[0].newInstance();
} catch(err1 e) { //Here meet my error
}
}
}
What shall I do to deal it?
Not to tell me to replace catch(err1 e) to catch(Exception e), for my Eclipse doesn't know a Exception can be thrown.
In addition,when I launch it,things as follows happened.
Exception in thread "main" java.lang.Error:Unresolved compilation problem:
Unreachable catch block for err1. This exception is never thrown from the try statement body
then I suddenly knew what I shall do...
The reflective method newInstance(), throws, amongst other things, InstantiationException. This will be thrown if an exception of any type is encountered in a constructor. You need to catch that one, and abstract your err1 using appropriate methods in the InstantiationException class.
newInstance() does not know about your specific exception per se, but rather it encapsulates it in the InstantiationException.
The Exception type is not known at compile time, since anything could be contained inside the Class array.
What you could do is check for the type in the catch block:
public class Example {
public static void main(String[] args) {
Class a[] = {Obj1.class};
try {
a[0].newInstance();
} catch (Exception e) {
if(e instanceof CustomException) {
System.out.println("CustomException");
}
}
}
}
class Obj1 {
Obj1() throws CustomException {
throw new CustomException();
}
}
class CustomException extends Exception {
}
Can't resist to mention: It is very helpful to others if you adhere to generally accepted coding/naming/formatting conventions.
This is something that's been bugging me for a while with regards to Program Flow.
I wanted to know if it's possible to catch an error from a Method in order to stop it from executing the Method that would normally follow it like the example bellow that I can't get to work.
public class MyClass {
public static void main(String[] args) {
// this method catches an exception and stops running
method01();
// this method will continue anyway which I don't want
method02();
};
};
I would normally have a static int variable that will initialize as 0 when the program is run and then if a method ever catches an exception it will increment that int and each method will only run if the int is 0.
This works but I was just wondering if I could replace the int shindig with exception handling.
Can you try:
try {
method01()
} catch (final Exception e) {
// do something
return; ///stop processing exit
}
the method01 will throw Exception:
private void method01() throws Exception {
// something
}
If you only want to terminate the whole program in case of an exception you just need to throw a RuntimeException without any further declaration. There are also specialized sub classes for explicit types of exceptions, like NullPointerException or IllegalStateException. See the "Direct Known Subclasses" section in the JavaDoc.
public class MyClass {
public static void main(String[] args) {
method01();
method02(); //method02 won't be called in case of an exception
}
private static void method01() {
// ...
if (true) // something goes wrong
throw new RuntimeException();
// further code won't be executed in case of an exception
}
private static void method02() {
System.out.println("method02 called");
}
}
Optionally it is possible to handle the exception with a try-catch-block:
public static void main(String[] args) {
try {
method01();
method02(); // method02 won't be called in case of an exception
} catch (Exception e) {
System.err.println("something went wrong");
}
}
// other code keeps unchanged...
If you want to enforce exception handling, you have to throw a subclass of Exception that is not derived from RuntimeException. But those exceptions have to be declared within the method Signature.
private static void method01() throws IOException {
throw new IOException();
}
You put method01 and method02 in to same try block:
public class MyClass {
public static void main(String[] args) {
try {
// This method catches an exception and stops running.
method01();
// This method will not continue if method01 have exception.
method02();
} catch (Exception e) {
e.printStackTrace();
}
}
// declare method01, method02, others...
}
Notice: You have mistakes at the end of code block ( }; }; )
Depends on what your method really does.
If your program should continue working also when an exception arise (e.g. NumberFormatException when parsing an input or in general a checked exception) a lot of people will suggest you to not use exception for flow control, but IMHO in very well defined cases (like NumberFormatException) the flow CAN be controlled by try catch statements and exceptions, it's really up to you.
A way to do so is to use the method returned parameter (also #Nikola answer works in this way, the point is to use the catch part of a try catch as flow control):
public class MyClass {
public static void main(String[] args) {
if(method01()) method02();
};
};
public boolean method01(){
try{
//some business
}catch(MyCheckedException e){
e.printStackTrace();
return false;
}
return true;
}
NB: You should use this approach only in well defined situations! If a file CAN be absent in a directory while opening it (checked FileNotFoundException), you COULD use this approach. If the file SHOULD be there and its not, the exception MUST stop the program.
What I want is a standard JDK class that look like this:
interface ExplodingRunnable {
void run() throws Exception;
}
Callable is no good, because its call() method is required to return a value, but I need a void.
Runnable is no good, because its run() method doesn't declare throws Exception.
I sort of need a combination of the two. Any ideas?
EDIT: I should have mentioned that I tried Callable<Void> but it requires you to define a method:
public Void call() {
// run your code;
return null; // ugly!
}
I'm looking for something a bit nicer.
Why do I want this?
I'm implementing a standard why of catching "will never happen" Exceptions (they will never happen, but various APIs define their methods throwing Exceptions) and throwing any Exceptions that might occur by wrapping them in an (unchecked) RuntimeException, so the caller can simply pass a "ExplodingRunnable" in and not have to code loads of perfunctory try/catch blocks that will never be exercised.
FINAL EDIT It looks like what I was looking for doesn't exist. The accepted answer is the closest to "correct", but it looks like there is no solution to answer the question as asked.
Could you just use Callable<Void>?
An interface with only one method, which returns void and throws Exception.
Among all java and javax classes, only one fits that description:
package java.lang;
public interface AutoCloseable
{
void close() throws Exception;
}
Well... the word "close" has many meanings...
You want to surround a bunch of statements with some extra handling, there is no sin to define your own interface here. You may find that your API requires users to learn 4 new phrases
Util.muckException( new ExplodingRunnable() { public void run() throws Exception
^1 ^2 ^3 ^4
You can actually cut down two, and user code would look like this
new MuckException(){ public void run() throws Exception
{
statement_1;
...
statement_n;
}};
public abstract class MuckException
{
public abstract run() throws Exception;
public MuckException()
{
try{ run(); }
catch(Exception e){ throw new Error(e); }
}
}
Just use Callable, ignore the return value and document things as ignoring the returned value and recommend returning null. Just because you can return something does not mean you have to.
I would just use Callable<Void> and learn to love it. ;)
You can have the checked exception not declared with the following.
Runnable runs = new Runnable() {
public void run() {
try {
// do something
} catch(Exception e) {
// rethrows anything without the compiler knowing.
// the method is deprecated but can be used on the current thread.
Thread.currentThread().stop(e);
}
}
});
Future future = executorService.submit(run);
try {
future.get();
} catch (ExecutionException ee) {
Throwable e = ee.getCause(); // can be the checked exception above.
}
and not have to code loads of perfunctory try/catch blocks that will never be exercised.
I had the same issue and fixed it a little differently
// Exceptions class
public RuntimeException wrap(Exception e) {
return e instanceof RuntimeException ? ((RuntimeException)e) : new RuntimeException(e);
}
// user code
try {
foo.bar();
} catch (Exception e) {
throw Exceptions.wrap(e);
}
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
}
public class MyClass {
public static void method() {
try {
// there is no compile time error for unnecessary catching 'Exception'
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
// why compile time error for unnecessary catching 'MyException' or
// 'CloneNotSupportedException' etc..
// ultimately Exception, MyException & CloneNotSupportedException all
// are checked exception
} catch (MyException e) {
e.printStackTrace();
}
}
}
class MyException extends Exception {
}
second scenario
---------------
public class MyClass {
public static void method() throws Exception {
}
public static void main(String[] args) {
// if Exception itself is not checked ,
// why compile time error occured for calling method(); ??
method();
}
}
Because RuntimeExceptions are subclasses of Exception class. Therefore, compiler can't determine if some code throws any runtime exception, as they might be thrown by jvm.
On the other hand - checked exceptions must be declared that are thrown by some method, so the compiler knows which exceptions could be thrown and can determine unnecessary catch blocks.
Methods declare what exceptions they throw. If you're catching anything that is not a superclass of any known exception types then the catching isn't necessary.
We have checked exceptions and unchecked Exceptions. CloneNotSupportedException is a checked exception: if a methods throws it, the caller needs to catch this type of exception. And in those cases, the jvm can detect, if it is catched while no method inside the try block ever throws it.
Exception itself is not checked.