is it possible to write a thrown exception to a file without using try catch blocks?
for example
public static void method() throws Exception, SQLException{
if(Exception is thrown){
write Exception to out.txt;
write SQLException to out.txt;
}
}
or do you have to do:
public static void method(){
try{
...
}catch(Exception ex){
write ex to file;
}catch(SQLException sqlex){
write sqlex to file;
}
}
In Java, I don't think it's possible.
However, if executed on *nix, you could just redirect all output to a file (or just error output). But that's not a generic solution.
You have to catch that exception some how. If you catch it and later on decide to write it a file is ok. Given what you have above I would suggest the second way because the if-statement has no way of actually getting the exception.
The only way to catch specific errors within a method is to use a Try/Catch block. However, it is possible to have a class catch all uncaught exceptions - ie anything that doesn't have a Try/Catch around it.
You can write a custom class to implement Java's UncaughtExceptionHandler interface.
import java.lang.Thread.UncaughtExceptionHandler;
public class CustomUncaughtExceptionHandler implements UncaughtExceptionHandler {
public void uncaughtException(Thread thread, Throwable throwable) {
/* Write to file here */
}
}
You then need to tell the Java Virtual Machine to redirect uncaught exceptions to your class.
public static void main(String[] args){
Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());
}
You cant do it with straight java unless you instrument the byte code (which you can do with an agent and something like asm). You can do it with an aspect, which is easier than the byte code instrumentation approach. Take aspectj for example. An aspect might be:
public aspect ExceptionAdvice {
pointcut allMethods() : execution(* *(..)) && !within(com.test.ExceptionAdvice);
after() throwing(Exception e) : allMethods() {
//write to a file or whatever - I'm lazy and just printed the stack
e.printStackTrace ();
}
}
Once you weave this to your application classes, all exceptions thrown will pass through the join point here. I just printed the stack but you can log it to a file or do whatever you want. When the join point completes, the exception continues to be thrown so the calling code has a chance to handle it. Obviously, you need to change the pointcut definition to suit your classes but this is the general idea.
No.
public static void method() throws Exception, SQLException{
if(Exception is thrown){
write Exception to out.txt;
write SQLException to out.txt;
}
}
Where does the Exception come from?
Btw.: You never declare the most abstract exception Exception to be thrown. Some RuntimeExceptions can occur nearly everywhere (Nullpointer, OutOfMemory) so it is useless to declare them everywhere. It's just noise.
public static void method() throws Exception, SQLException{
try{
...
}catch(Exception ex){
write ex to file;
}catch(SQLException sqlex){
write sqlex to file;
}
}
But if you catch it, you usually don't throw, and therefore don't declare at all to throw Exceptions.
In the second block you already catched the exception, so no need for throws Exception, SqlException.
An exception is detected on a regular line of code, so you can't add an if to each and every one. Yes, try/catch(write) is the only way.
Unless ... you use if/else instead of exception handling
You will need to catch the exception and rethrow it.
public static void method() throws Exception, SQLException{
try{
...
}
catch(SQLException sqlex){
write sqlex to file;
throw ex;
}
catch(Exception ex){
write ex to file;
throw ex;
}
}
Related
I've a question about catching an exception in method that use another method that can throw an exception.
public void methodA(File file) {
try {
}
catch (IOException ex) {
}
}
public void methodB() {
// do something with the file
File file = new File("/example.txt");
methodA(file);
}
Do I need to create a try and catch block inside the methodB? Or it's enough to catch the exception in that case IOException inside methodA?
It depends on what you'd like to achieve.
In your code sample, methodA will handle an exception and continue a methodB execution with no interrupts. This is probably not what you'd like since there was an error reading file and it should be gracefully handled.
Most likely you'd like to bubble your exception up the execution chain and handle it in a relevant object (eg. some error handler that can output error message to an user) .
Bubble up your exception like this:
public void methodA(File file) throws CustomUserInputException {
try {
}
catch (IOException ex) {
throw new CustomUserInputException(ex, "Error opening file" + file.getPath());
}
}
and then handle it in an approptiate object like this:
public void methodB() {
// do something with the file
File file = new File("/example.txt");
try {
methodA(file);
}
catch (CustomUserInputException ex) {
showErrorToAnUser();
stopStandardProgramExecution();
}
}
No, in this case you do not need to in methodB - but you might want to, because methodA might throw other errors beside IOException.
It depends on your intention and the type of exception - if your methodA throws a checked exception methodB has to either catch it or declare that it throws that exception. If its an RuntimeException, methodB might catch it or ignore it.
In most techstacks, checked exception are rare, most think they are a failed experiment.
Lastly, whether a method needs to catch exception or not depends - can methodB conceivably handle the error? If so, catch it there - if not, let it bubble up, e.g. to a general error handler or even crash the program. nothing is more annoying than a program which catches every error and does the wrong thing.
You can't since the exception can only move up the callstack. If the program also ran methods following the exception, whats the point of even creating an exception in the first place?
Try to handle exceptions where they occour. If there is a possibility of an exception when creating a File, it should be handled where the file is created. Otherwise the overhead of making sure that incoming values are not exceptions would be way too high.
I would suggest either catching it inside methodBor passing the file name into methodA and have it create the File and catch any exceptions.
I am trying to understand exception handling in Java and i keep running into variations of the below mentioned confusing statement in several articles -
There are several reasons why catching instance of java.lang.Throwable is bad idea, because in order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
This is from http://javarevisited.blogspot.com/2014/02/why-catching-throwable-or-error-is-bad.html#ixzz4hQPkFktf
However, this code compiles -
class CatchThrowable
{
void function()
{
try
{
throw new Throwable();
}
catch (Throwable t)
{
}
}
public static void main(String[] args)
{
try
{
}
catch (Throwable t)
{
}
}
}
Both main and function are able to catch Throwable without declaring that they throw it. My understanding is that the throws keyword is used to declare the checked exceptions which a function throws, not those which it catches. Please clarify the quoted statement.
The statement:
order to catch them you have to declare at your method signature e.g. public void doSomething() throws Throwable.
is basically wrong.
You just have to understand the following. There is a exception Hierarchy
A method can throw all types of exception, it just depends on your needs which one you catch and which one not.
It is also not a good idea to catch Error (which includes that you should also not catch Throwable) because there are some severe JMV-VirtualMachineError's like OutOfMemoryError which you usually not should catch.
But this has nothing to do which the fact, what a method declares in its throws part.
So I thought I had a good basic understanding of exception-handling in Java, but I was recently reading some code that gave me some confusion and doubts. My main doubt that I want to address here is when should a person use throws in a Java method declaration like the following:
public void method() throws SomeException
{
// method body here
}
From reading some similar posts I gather that throws is used as a sort of declaration that SomeException could be thrown during the execution of the method.
My confusion comes from some code that looked like this:
public void method() throws IOException
{
try
{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
Is there any reason that you would want to use a throws in this example? It seems that if you are just doing basic exception-handling of something like an IOException that you would simply need the try/catch block and that's it.
If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.
Typically, if you are not going to do anything with the exception, you should not catch it.
The most dangerous thing you can do is catch an exception and not do anything with it.
A good discussion of when it is appropriate to throw exceptions is here
When to throw an exception?
You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.
See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.
The code that you looked at is not ideal. You should either:
Catch the exception and handle it;
in which case the throws is
unnecesary.
Remove the try/catch; in which case
the Exception will be handled by a
calling method.
Catch the exception, possibly
perform some action and then rethrow
the exception (not just the message)
You're correct, in that example the throws is superfluous. It's possible that it was left there from some previous implementation - perhaps the exception was originally thrown instead of caught in the catch block.
The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.
Something like:
public void method() throws Exception {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
or
public void method() {
try {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
} catch(IOException e) {
System.out.println("Catching IOException");
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
System.out.println(e.getMessage());
}
}
In the example you gave, the method will never throw an IOException, therefore the declaration is wrong (but valid). My guess is that the original method threw the IOException, but it was then updated to handle the exception within but the declaration was not changed.
This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.
Lets say there is
public static void main(String[] args) {
try {
// do nothing or throw a RuntimeException
throw new RuntimeException("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
The output is
test
Exception in thread "main" java.lang.RuntimeException: test
at MyClass.main(MyClass.java:10)
That method does not declare any "throws" Exceptions, but throws them!
The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method.
It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception
Now, if we have
public static void main(String[] args) throws Exception {
try {
throw new Exception("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.
In Java, is it possible to make a method that has a throws statement to be not checked.
For example:
public class TestClass {
public static void throwAnException() throws Exception {
throw new Exception();
}
public static void makeNullPointer() {
Object o = null;
o.equals(0);//NullPointerException
}
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm forced to handle the exception, but I don't want to
}
}
You can try and do nothing about it:
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) { /* do nothing */ }
}
Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by #BaileyS.)
Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:
// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
throw new RuntimeException();
}
Classes that extend RuntimeException won't require a throws declaration as well.
And a word from Oracle about it:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
There are 3 things you can do :
Throw a RuntimeException (or something extending a RuntimeException, like NullPointerException, IllegalArgumentException,...), you don't have to catch these as they are unchecked exceptions.
Catch the exception and do nothing (not recommended) :
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) {
// Do nothing
}
}
Change exceptionTest () declaration to say that it throws an Exception, and let the method calling it catch the Exception and do what is appropriate :
public static void exceptionTest() throws Exception {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm no more forced to handle the exception
}
In Java there is two kinds of Exceptions, Checked Exceptions and Unchecked Exceptions.
Exception is a checked exception, must caught or thrown.
NullPointerException is a RuntimeException, (the compiler doesn’t forces them to be declared in the throws claus) you can ignore it, ,but it still may occur in the Runtime, and your application will crash.
From Exception documentation:
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.
From the RuntimeException documentation:
RuntimeException is the superclass of those exceptions that can be
thrown during the normal operation of the Java Virtual Machine.
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.
No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it.
Check this and this.
Throw a RuntimeException or an exception which is derived from RuntimeException. Then the compiler will not force you to catch it.
The other answers are right, in that they correctly tell you what you should do, but it is actually possible to throw a undeclared checked exception. There are a few ways this can be done; the simplest is:
public void methodThatSecretlyThrowsAnException() {
Thread.currentThread().stop(new Exception());
}
or if your goal is to wrap an existing method that does declare its exception
public void methodThatSecretlyThrowsAnException() {
try {
methodThatAdmitsItThrowsAnException();
} catch(final Exception e) {
Thread.currentThread().stop(e);
}
}
(Needless to say, you should never do this.)
Just catch an exception and dont do any thing with it, leave it as it is and catch the generic exception in case you are not aware of the specific exception
try{
//Your logic goes here
}
catch(Exception e)//Exception is generic
{
//do nothing
}
AS I know, it's impossible in the case. Only unchecked exception, compiler can skip to check. such as RuntimeException.
You can use a loophole in the Java Compiler. Add the following code:
public RuntimeException hideThrow(Throwable e) {
if (e == null)
throw new NullPointerException("e");
this.<RuntimeException>hideThrow0(e);
return null;
}
#SuppressWarnings("unchecked")
private <GenericThrowable extends Throwable> void hideThrow0(Throwable e) throws GenericThrowable {
throw (GenericThrowable) e;
}
You can catch the exception, then invoke hideThrow with the exception to throw it without the compiler noticing. This works because of type erasure. At compile time, GenericThrowable represents RuntimeException because that is what we are passing. At run time, GenericThrowable represents Throwable because that is the basic type in the type parameter specification.
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.
If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.
For example:
private class UnlikelyException extends RuntimeException {
public UnlikelyException (Exception e){
super (e);
}
}
Then wrap your code with a try-catch block and throw your exception, which you don't have to catch
try {
// Your code
} catch (Exception e) {
throw new UnlikelyException(e);
}
I'm reviewing a midterm I did in preparation for my final exam tomorrow morning. I got this question wrong, but there's no correct answer pointed out, and I neglected to ask the prof about it.
Consider the following code snippet:
public static void main(String[] args) throws FileNotFoundException
Which of the following statements about this code is correct?
The main method is designed to catch and handle all types of exceptions.
The main method is designed to catch and handle the FileNotFoundException.
The main method should simply terminate if the FileNotFoundException occurs.
The main method should simply terminate if any exception occurs.
I had chosen the second option.
Answer is number 4,
4.- The main method should simply terminate if any exception occurs.
The throws clause only states that the method throws a checked FileNotFoundException and the calling method should catch or rethrow it. If a non-checked exception is thrown (and not catch) in the main method, it will also terminate.
Check this test:
public class ExceptionThrownTest {
#Test
public void testingExceptions() {
try {
ExceptionThrownTest.main(new String[] {});
} catch (Throwable e) {
assertTrue(e instanceof RuntimeException);
}
}
public static void main(String[] args) throws FileNotFoundException {
dangerousMethod();
// Won't be executed because RuntimeException thrown
unreachableMethod();
}
private static void dangerousMethod() {
throw new RuntimeException();
}
private static void unreachableMethod() {
System.out.println("Won't execute");
}
}
As you can see, if I throw a RuntimeException the method will terminate even if the exception thrown is not a FileNotFoundException
Dude, a little late, but answer is Number 3.
Number 1 is false because it is not handling FileNotFoundException
Number 2 is false for the same reason.
Number 3 is true. If a FileNotFoundException is thrown, the main method will terminate.
Number 4 is false. It would not terminate in case of ANY exception. It would terminate only in case of unchecked exception or FileNotFoundException. If there are not other checked exceptions declared in the 'throws' clause, it means they are being handled within the method.
The main method is not catching any exceptions, instead it handles the FileNotFoundException by throwing it to the source which invoked the main method.
The system runtime launches the JVM classes, one specific class among the JVM classes invokes the main method.
The handling for the main method's throws is at the mercy of the JVM classes in that case.
You can read about it in the Java language specification provided by Oracle.
Additionally you can view the source code for some of the JVMs available out there, going that path though takes you away to other programming languages,OpenJdk.
I thought of sharing my small humbled research crust in that topic, hope it helps curious ones :)
I agree with some other answers that the correct answer to the question is option 3. Option 4 says:
The main method should simply terminate if any exception occurs.
Note the "any" in this option. Here's an example of code in which an exception occurs, but main() does not terminate:
public static void main(String[] args) throws FileNotFoundException {
try {
methodThatThrowsACheckedException();
} catch (SomeCheckedException e) {
// do something to handle this exception
}
}
In this code an exception occurs, but the method does not terminate, as it's been setup to handle this exception. If the exception were an uncaught UncheckedException, then the method would terminate, of course. The point of option 4, though, is that any counter-example invalidates it, since it says "any" exception occurs.
Option 3, however, limits this termination to only occur when the exception in the method's signature is thrown:
The main method should simply terminate if the FileNotFoundException occurs.
The reason option 3 makes more sense is because code like the following does not make sense in practice:
public static void main(String[] args) throws FileNotFoundException {
try {
methodThatThrowsFileNotFoundException();
} catch (FileNotFoundException e) {
// do something to handle this exception
}
}
It doesn't make much sense to declare that a method throws an exception, but catch that exception in the method (unless, perhaps, you re-throw it after doing something, in which case option 3 still holds, as the method terminates eventually).
With only the declaration of main(), it is impossible to say which answer is objectively correct. Any of the statements could be true, depending on the definition of the method.
The main method is designed to catch and handle all types of exceptions.
The main method is designed to catch and handle the FileNotFoundException.
Both of the above statements are true of the following:
public static void main(String[] args) throws FileNotFoundException {
while (true) {
try {
doSomething();
}
catch (Exception e) {}
}
}
The declared exception is never thrown by main(), but that is not an error; just pointless and misleading.
The main method should simply terminate if the FileNotFoundException occurs.
The main method should simply terminate if any exception occurs.
Both of the above statements are true of the following:
public static void main(String[] args) throws FileNotFoundException {
try {
doSomething();
}
catch (Exception e) {
return;
}
}
Of course, we can guess at the intention of the question based on what a decent and reasonable programmer might intend to communicate with this method signature. Which would be that they intend for the method to throw FileNotFoundException, and necessarily handle other checked Exceptions. We can also reasonably assume that "handle" does not just mean "process", but specifically that it will not (re-)throw such an exception.
These assumptions immediately rule out #1 and #2.
The remaining question is whether "simply terminate" includes throwing an exception, or only an explicit return/System.exit(). In the former case, both of #3 and #4 could still be true:
public static void main(String[] args) throws FileNotFoundException {
try {
doSomething();
}
catch (FileNotFoundException fnfe) {
throw fnfe;
}
catch (Exception e) {
return;
}
}
In the latter case, neither #3 nor #4 can be true while also satisfying the assumption that main() will throw FileNotFoundException.
In sum, the options are not worded well. If I had to pick an answer, it would be #3 based on the logic of MartinV's answer. My assumption would be that the word "should" in #3 was an unfortunate choice by the professor, and that something like "may" would have been a better option. It would also have been a good idea to use more precise language than "simply terminate" (and, arguably, "handle").
The answer is both 2 & 3.
2.The main method is designed to catch and handle the FileNotFoundException.
3.The main method should simply terminate if the FileNotFoundException occurs.
But if fails to handle the exception even though it is designed to handle it and the programs gets terminated abnormally.
throws keywords is used to make JVM handle the exceptions which we are lazy to handle, it compiles successfully but shows the exception during runtime(if u handle it in main method then it compiles and runs successfully).
4.The main method should simply terminate if any exception occurs.
Is not correct always because the exceptions which occurs may be handle in the main method.
1.The main method is designed to catch and handle all types of exceptions.Is incorrect as JVM doesn't handle unchecked exceptions.