Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am studying Java these days, and I have realized that it is important to handle exceptions in my codes.
I just what to ask how to handle exceptions with various methods?
Is it to examine the method I use to see what exception the method has thrown? In the example below I have to see what exception method m() throws.
try {
m();
} catch(SomeException e) {
...;
}
Is there any train of thought to handle exceptions when programming with Java?
The main skill to learn is how to not catch exceptions, but let them propagate up the call stack into the exception handler at the appropriate level.
Some rules of thumb:
catch the exception early (close to where it appeared) only if you have an actual escape route, a different way to complete the request in progress;
either log the exception or rethrow it, never both;
the place high up in the call stack is called the exception barrier: this is the unique place where to log the exception as an error;
don't be mislead by checked exceptions: most of the time the checked/unchecked distinction is not salient. Rethrow the checked exception (wrapped in a RuntimeException) when you have no code in mind to recover from it, which is the case most of the time. You could also declare the exception in your method header, but that is rarely practical;
be very careful not to let an exception result in a resource leak: all the acquired resources must be released in the finally block.
Reading these lines you'll note that most issues around exceptions are not demonstrable on minimal, textbook examples. Exceptions are about the information and control flow in fat codebases.
You really need to do a few tutorials on exception handling, you could use:
try {
m();
} catch(Exception e) {
e.printStackTrace();
}
to see what exception is being thrown and then read up on it.
Usually you need to log the exception, at least. And when
catching the exception make sure your catch block is not empty.
Some of them you can handle, some you cannot (for them you
usually need to fix your code as they indicate a bug in it).
So some are expected, others are programming errors.
Some are RuntimeExceptions (unchecked), others are not RuntimeExceptions
(i.e. are checked). RuntimeExceptions you don't need to declare in methods
or catch (i.e. you're not forced to do so by the language itself).
http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html
http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
The subject is too broad.
Try with samples like this as mentioned in below links that will give you clear clarification about the exception handling Do it with practically bro...
The 'Throwable' class is the superclass of all errors and exceptions in the Java language
Exceptions are broadly classified as 'checked exceptions' and 'unchecked exceptions'. All RuntimeExceptions and Errors are unchecked exceptions. Rest of the exceptions are called checked exceptions. Checked exceptions should be handled in the code to avoid compile time errors.
Exceptions can be handled by using 'try-catch' block. Try block contains the code which is under observation for exceptions. The catch block contains the remedy for the exception. If any exception occurs in the try block then the control jumps to catch block.
If a method doesn't handle the exception, then it is mandatory to specify the exception type in the method signature using 'throws' clause.
We can explicitly throw an exception using 'throw' clause.
http://java2novice.com/java_exception_handling_examples/
http://www.programmingsimplified.com/java/tutorial/java-exception-handling-tutorial
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
There is a compile time and a run time of Java code. There are checked exceptions and unchecked exceptions. Both, checked exceptions and unchecked exceptions, happen at run time.
None-the-less the base class of the unchecked exceptions is not called UncheckedException but RuntimeException. This is not directly intuitive.
How can we access the choice of name from a logical point of view? Why is it not just called UncheckedException vs. CheckedException?
Once you understand the logic behind the choice of a name, it is much more easy to work with it.
Javadoc of RuntimeException says:
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
It's called "Runtime" because it is the superclass of exceptions that can be thrown by the "Runtime System", aka the Java Virtual Machine and the Runtime Library.
It's not about "at runtime", but about the "runtime system".
The exceptions are those that the JVM can generate, such as NullPointerException, ArrayIndexOutOfBoundsException, NegativeArraySizeException, ArrayStoreException, ArithmeticException, as well as common exceptions from the "Runtime Library" that shouldn't normally be caught (unchecked exceptions), such as IllegalArgumentException NoSuchElementException, etc.
The compiler has no default instructions or algorithm to handle your run time exceptions. that's why its called Run Time Exceptions.
A compile time exception is NOT an exception, it is an error in the code.
Throwable is at the top off all exceptions. Underneath Throwable you have Error and Exception. Underneath Exception you have RuntimeException.
Java has two types of exceptions - checked and unchecked. Checked exceptions are enforced by the compiler (you have to declare them in the throws clause and catch them eventually). Unchecked exceptions are not enforced for catching or declaring in throws clause.
Throwable exists so that there is a parent for all exception types. You should never declare that you throw Throwable and never catch it (unless you really really really know what you are doing).
Error exists to indicate issues with the runtime environment, things that your program probably cannot recover from, such as a badly formatted class file or the VM running out of memory. You should not catch an Error unless you really know what you are doing.
Exception exists as the root for all non-programmer errors (see RuntimeException for the "exception" to this) , such as a file cannot be created because the disk is full. You should not throw, throws, or catch Exception. If you have to catch Exception make sure you know what you are doing.
RuntimeException exists to indicate all programmer error, such as going past the end of an array or calling a method on a null object. These are things that you should fix so that they do not throw exceptions - the indicate that you, the programmer, screwed up the code. Again, you should not catch these unless you know what you are doing.
Read : https://docs.oracle.com/javase/tutorial/essential/exceptions/
Is it just an unfortunate choice of name?
It is just a way to differentiate them.
Checked and no checked exceptions derive from the same base class : Exception.
Exception is checked at compile time and RuntimeException is not.
The Runtime prefix conveys that the RuntimeExceptions are designed to be thrown at runtime without that client code needs to handle them at compile time.
As said in my comment : Exception and UnCheckedException would be more natural as we often refer to checked and unchecked exceptions as we talk about them. Now, things are done since a long time and the API cannot be modified and replaced.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am currently wrapping a C Library in Java, making it easier to use and work within OO-Programming. The C Library uses error codes (int return value) and Out-Parameter for data manipulation. I am not necessarily a fan of error codes, so I would like to create some custom Exception classes that I can throw if my library detects an error code other than "success".
The only problem is that the amount of Exceptions that might be raised by every single method is very high (There are some error codes that can be returned from every C library function, like "Device_Not_Connected"). It has been a while since I last programmed in Java, so, I really don't know what the situation is with Exceptions in Java.
Are methods that throw a lot of different exceptions bad design?
Do I have to handle the exceptions, or is there a way of simply ignoring it?
If I can ignore an exception, does it bubble up the call tree (like in Python for example)?
Are there any alternatives to exceptions in Java besides error codes and no-ops?
Are methods that throw a lot of different exceptions bad design?
If used right clearly no! An exception basically is just a possible return state which is out of the scope of the technical purpose of the method. E.g. if the method should read an value from a device null or any value should be returned using the return type. But throwing a custom DeviceNotConnectedException to state that something went wrong when you are not able to read a return value instead of simply returnung null is 100% best practice. And if 10 things can go wrong then it is okay to state 10 possible exceptions.
Do i have to handle the exceptions, or is there a way of simply ignoring it?
When you don't catch an exception you will have to declare the method it occurs in with "public void myMethod() throws MyExcp {..}" and so on in every method calling this method, that method caller and so on. If you hand it to the main-method and it's not handled there it will crash the programm.
If i can ignore an exception, does it bubble up the call tree (like in Python for example)?
See above.
Are there any alternatives to exceptions in Java besides error codes and no-ops?
Not as far as I know but I'm not an expert.
You should definitely throw an exception if something goes wrong that is connected to IO (files, devices, user input). You do not need to define a different exception class for all the different error codes. If the handling of the error codes is quite similar, you can use the same exception, like
throw new IOException("Device not connected");
If possible, you should avoid throwing around too many exceptions that are connected to wrong parameters etc. Establish check functions for the user (like "containsKey") so that need not "try and catch" such things.
You could create an inheritance hierarchy for your Exception classes, so that a method signature defines few [or even only one] general Exception class, regardless how many specific Exceptions you throw in the method's body.
public void myMethod() throws MyGeneralException {
...
throw new MySpecific1Exception();
.....
throw new MySpecific2Exception();
}
The callers will have the freedom of choice to handle specific Exceptions or the general ones.
Option 1:
try {
myMethod();
} catch (MyGeneralException e) {
....
}
Option 2:
try {
myMethod();
} catch (MySpecific1Exception e) {
....
} catch (MySpecific2Exception e) {
....
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
There are so many exceptions, and it is not easy to remember. Is there any rule to know which kinds of exception will fall in which type (runtime vs checked), so that we know in which case we need to catch and in which case we just throw an exception? Thanks!
First of all, no exceptions are compile-time exceptions. The differentiation is checked exceptions vs. unchecked exceptions. The differentiation is made by the compiler by behaving as if each and every operation (method, constructor and initializer block) signature always implicitly includes throws Error, RuntimeException in its declaration. This way, the handle-or-declare rule, which means the compiler forces you to either handle an exception in a catch clause or declare an exception with a throws declaration is disabled for Error and RuntimeException - they are always implicitly declared.
So we overall have the following categories:
Compiler-treatment:
unchecked exception (handling is optional): RuntimeException and Error
checked exception (handle-or-declare rule applies): All other exceptions, including Throwable.
Categories:
Error - we usually do not catch these.
RuntimeException - catching depends on root cause.
Exception - we must handle or declare them (compiler enforces).
Error is easy to remember. If the VM or one of its APIs thinks it's a defect of the VM or the API that causes the issue, it's an Error. Usually we do not catch Errors, although there are a few prominent examples, like these:
catching OutOfMemoryError in resource allocating code to let the application continue after displaying an error message to the user. I.e. the user wants to load an image that's too big.
catching AssertionError in Unit Test frameworks. (They actually catch Throwable, but AssertionError is treated specially, it's a test failure, not a test error.)
Runtime exceptions are exceptions which do not happen if the program was written correctly, as long as the conditions that could lead to these exceptions do not depend on the user. For example, Integer.parseInt(String) throws NumberFormatException. If the String that is converted is coming from the program itself, it should be correct and we wouldn't care about the exception. If the String that is converted is coming from the user, we would usually rather catch NumberFormatException than letting the user crash the program by means of faulty input.
Other exceptions are used where the fault condition is somewhat likely but the program is always expected to handle them in some way. For example, if you open a file, it could always be that the file doesn't exist, cannot be read due to lack of permissions or locking, or that the storage is corrupt.
If you want to be new about things just catch everything... (horrible idea though only for the lazy) Otherwise look at the javados and it will tell you what is throw with each method.
try {
// this code
} catch (Exception e) {
e.printStackTrace();
}
Yeah if you have an issue at compile it means it just doesn't compile therefore doesn't exist and cannot run.
Do not catch RuntimeExceptions and Errors, catch other exceptions or add throws to method declaration
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Why is catching a RuntimeException using catch(Throwable exc) {} not considered a good programming practice? What is the right way to handle RuntimeExceptions?
Also, why does catch(Exception exc) {} not catch RuntimeException? How is this behavior implemented?
Usually, a RuntimeException indicates a programming error (in which case you can't "handle" it, because if you knew to expect it you'd have avoided the error).
Catching any of these general exceptions (including Throwable) is a bad idea because it means you're claiming that you understand every situation which can go wrong, and you can continue on despite that. It's sometimes appropriate to catch Exception (but not usually Throwable) at the top level of the stack, e.g. in a web server - because usually whatever's gone wrong with a single request, you normally want to keep the server up and responding to further requests. I don't normally catch Throwable, as that includes Error subclasses which are normally used to indicate truly catastrophic errors which would usually be best "handled" by terminating the process.
Fundamentally, when there's an error you need to be very cautious about continuing with a particular task - you need to really have a pretty good idea about what the error means, as otherwise you could go ahead with a mistaken assumption about the state of the world, and make things worse. In most cases (not all), simply giving up on a request is better than trying to carry on regardless of a mysterious failure. (It does very much depend on context though - you might not care what went wrong when trying to fetch one piece of secondary information, for example.)
As for catching Exception not catching RuntimeException - that's simply not true. The only odd thing about RuntimeException is that it (and subclasses) are unchecked exceptions, whereas Exception and all other subclasses of Exception are checked.
It boils down to the different types of exceptions there actually are.
Checked exceptions (that is, exception classes that extend Exception) are typically errors you can recover from.
Unchecked exceptions (that is, exception classes that explicitly extend RuntimeException) are those that indicate an error in either expected behavior or program state. You wouldn't get a NullPointerException if the state of an object wasn't null when you dereferenced it, of course.
Blanket-catching everything - either Exception or Throwable, which is far worse - is not a good practice because you're assuming that you can recover from any exceptional behavior. There are some cases in which you shouldn't, or realistically can't (i.e. OutOfMemoryError for catch(Throwable t)). Further, catching runtime exceptions indicates a code smell; it means that you're covering up a coding error.
Be explicit about what it is you're catching.
Aside: Yes, catch Exception will also catch RuntimeException, since Exception is a superclass of RuntimeException. Just the same, Throwable will catch Exception and Error, which is why it's worse to write catch(Throwable t).
Throwable is super class of all Exception checked and unchecked(RuntimeException) and error.
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
java.lang.Error
Ideally catching error is not a good practice.
And as RuntimeException extends Exception so it catches all RuntimeExcption's.
Is there any reason for not converting the following code
try {
// Do something
} catch (XException e) {
e.printStackTrace();
} catch (YException e) {
e.printStackTrace();
} catch (ZException e) {
e.printStackTrace();
}
to this:
try {
// Do something
} catch (Exception e) {
e.printStackTrace();
}
I know the 2nd one catches all kinds of Exceptions, and I don't mind that. And let's say I want to handle all exceptions in the same way. Is the performance difference considerable?
The Java try/catch mechanism has been so highly tuned in successive JVM's that their performance is never something you should be explicitely worried about. Rather, you should be coding those blocks according to whether you need to handle the caught error scenarios in different ways. In your example you are just printing a stack trace so it is not beneficial to catch the specific errors - but your use case will actually determine wether you should be rolling up or down for these try/catch blocks.
This separation is only because you would be able to perform different task for different exceptions. Like if you receive parse exception and you get IO exception so you would know exactly what to do with each exception.
In newer version this blocks has been minimized with multiple exception in on block which will help the coder and increase the readability. e.g.
try {
// Do something
} catch (XException | YException | ZException e) {
e.printStackTrace();
}
I wouldn't worry about performance at the moment (unless you know it's a real issue).
You may want to convert for readability (if the same action is performed for each type of excpeption), but don't forget that catching Exception will catch lots of other stuff besides XException, YException, ZException. Is there a useful base class for those, and can you catch that instead ?
Occasionally you may want to perform different actions on different exceptions.
Even if you don't you still help other programmers see the complete picture rather than hiding it in one big Exception; which also happens to catch all Runtime exceptions.
The main reason you catch the exceptions separately is you may want to do something different based on which exception has been thrown. For example when parsing a file, you may want to throw a FileNotFoundException, or an IndexOutOfBounds exception. One tells you you cannot find the file to parse, while the other tells you there was a problem during the parse itself. It's much more informative to handle these separately as they are entirely different problems. For example the end user could receive different error messages based on the exception thrown.
There is a difference in catching RunTimeExceptions like NullPointerException. Those will be caught in the second case but not in the first.
In the vast majority of situations you want exception handlers to be as specific as possible so that your code is resilient and adopts an appropriate recovery strategy in the event that an exception occurs. Taking a general approach to exception handling is unwise as the handler must react to any exception possibility which this can result in code being more error-prone when unexpected exceptions are caught which the handler was not intended to handle. In essence exception handlers with the clause catch (Exception e) is the lazy approach.
In my experience the motivation for placing an exception handler around a block of code is to catch a specific exception or set of exceptions. Therefore at the time of conception you know the exceptions you want to catch anyway, why generalise and use the Exception class?
I'd advise reading two things to gain appreciation for specific exception handling:
Effective Java Second Edition - Joshua Bloch : Chapter 9
The Java tutorial on Exceptions : Advantages of Exceptions
IMHO it is just a question of handling all errors the same way or some in a different way.
First one is useful when you want to handle different exceptions in different ways and in second case you are handling all exception in same way. Use second way when you perfectly don't know which exception will occur and if you know you can use the first one.
Not much difference from a technical perspective. The second version will catch all XYZ exceptions plus any RuntimeException that may be thrown in the try block. Check, if that is OK.
If the catch handlers all do the same for any thrown exception, then I see no problem with grouping them. Although it is not very common (in production code) to have equal catch handlers, usually they do different things or log different messages.
Reason is to handle different exceptions for ex. for a sql exception you may want to rollback the transaction but for a io exception for an unfound file u may want to create that file etc.
If we consider the performance there is no difference between handling in one catch block or with multiple.
exception can occurs for many reasons
A file that needs to be opened cannot be found (fileNotFoundException or InputStreamExcep)
A user has entered invalid data.
network connection has been lost or the JVM has run out of memory.
Types of exceptions:
Three Kinds of Exceptions are:
Checked exception:
A checked exception is an exception that a user error or a problem which is not foreseen by the programmer.
Example:if a file is to be opened, but the file is not found, an exception occurs. These exceptions cannot be ignored at the time of compilation.
Unchecked exceptions: A runtime exception is an exception that occurs that probably ignored by the programmer.It is also known as runtime exceptions.these are ignored at the time of compliation.
Errors: problems that arise beyond the control of the programmer.
Example, if a stack overflow occurs, an error will arise. These are ignored at the time of compilation.
Catching Exceptions:
Byusing try/catch, we can handle the exception.try block is placed around the code that might generate an exception.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Multiple catch Blocks:
A try block can be followed by multiple catch blocks.