java exception chaining question - java

Imagine I have the methods:
public static void funcA() {...}
public static void funcB()
{
byteBuffer.wrap(someByteArray, 0, someByteArra.length);
}
IN JAVA API:
public static ByteBuffer wrap(byte[]array, int offset, int length)
{
try {
return new HeapByteBuffer(array, offset, length);
} catch (IllegalArgumentException x) {
throw new IndexOutOfBoundsException();
}
}
function chain: funcB() -> ByteBuffer.wrap()
My question is how come funcB does not need to do a try-catch block around this java api method that throws an exception. funcB compiles fine without a try-catch block. I believe the answer has to do with the fact that the java api method throws an exception BUT IS NOT DECLARED as "throws IndexOutOfBoundsException"
function chain: funcA() -> funcB() -> ByteBuffer.wrap(...)
My next question is when I DO change funcB to "funcB() throws IndexOutOfBoundsException" how come funcA doesn't need to catch funcB's thrown exception? Does the compiler dig deep and realize that ByteBuffer.wrap(...) isn't declared as "wrap() throws IndexOutOfBoundsException" so all callers don't actually need to catch anything even sub-callers (funcB in this case) actually are declared as "funcB throws IndexOutOfBoundsException"?
Sorry if that was confusing or hard to understand.
Please help.
jbu

IndexOutofBoundsException extends RuntimeException. Its a runtimeexception, doesn't need to be checked.
See unchecked exceptions - the controversy.

At the top of the exception hierarchy is java.lang.Throwable. It is a checked exception (the compiler forces you to catch it or declare that you throw it).
Below Throwable there is Exception, also a checked exception, and Error, an unchecked exception (the compiler doesn't warn you about it).
Below Exception there is RuntimeException, also an unchecked exception.
The way that the designers of Java intended exceptions to be used is:
Exception, things that can go wrong
Error, low level things that can go wrong and a program cannot recover from
RuntimeException, programmer errors (like going past the end of an array, or calling a method on null).
The idea behind not having to catch unchecked exceptions is that they indicate failures (VM level, or programmer) that either you cannot handle (VM error) or should not exist in a properly debugged program (programmer mistake).
Not everyone agrees with the intent of the designers of Java on this and chose to use RuntimeException to mean things other than programmer mistake.

Related

java, throwing unchecked exception by making an object of Throwable [duplicate]

I am having some problems with understanding the differences between checked and unchecked exceptions in Java.
Firstly, checked exceptions are supposed to look for abnormalities during compile time. Examples provided in different sources cite database connectivity, file handling as some of them, while unchecked exceptions are supposed to look for errors on the programmer's part, like indexing beyond the range of an array, etc.
Shouldn't it be the other way round? I mean, database connectivity is done during run-time, right? Same goes for file-handling. You don't open a file-handle during compile time, so why a possible error on that is looked for during compile-time? On the other hand, indexing an array beyond its range is already done in the program, which can be checked during compile time (if the abnormal index is supplied by user during run-time, then it's okay for it to be a run-time problem). What am I missing here?
2 Secondly, how can RunTimeException, itself being unchecked, subclass Exception, which is checked? What does this signify?
I found an example in Herbert Schildt's book explaining the usage of checked exceptions:
class ThrowsDemo {
public static char prompt(String str)
throws java.io.IOException {
System.out.print(str + ": ");
return (char) System.in.read();
}
public static void main(String args[]) {
char ch;
try {
ch = prompt("Enter a letter");
}
catch(java.io.IOException exc) {
System.out.println("I/O exception occurred.");
ch = 'X';
}
System.out.println("You pressed " + ch);
}
}
Is the throws clause necessary here? Why can't I do it just normally with a try-catch statement like this (sorry I don't know how to simulate an IO Exception, so couldn't check it myself!):
class ThrowsDemo {
public static char prompt(String str) {
System.out.print(str + ": ");
return (char) System.in.read();
}
public static void main(String args[]) {
char ch;
try {
ch = prompt("Enter a letter");
}
catch(java.io.IOException exc) {
System.out.println("I/O exception occurred.");
ch = 'X';
}
System.out.println("You pressed " + ch);
}
}
CheckedException needs to be handled by the caller, Unchecked exception don't.
So, when you design your application you should take in mind what kind of exceptional situation you are managing.
For example, if you design a validation method that checks the validity of some user input, then you know that the caller must check the validation exception and display the errors to the user in a nice looking way. This should be a checked exception.
Or, for those exceptional conditions that can be recovered: imagine you have a load balancer and you want notify the caller that one of the "n" servers is down, so the caller must recover the incident re-routing the message to another server; this should be a checked exception, because it is crucial that the caller (client) tries to recover the error, and don't just let the error to break the program flow.
Instead, there are many conditions that should not happen, and/or should instead break the program. For example, a programming error (like division by zero, null pointer exception), a wrong usage of an API (IllegalStateException, OperationNotSupportedException), an hardware crash, or just some minor situation that are not recoverable (lost connection to a server), or a doomsday :-) ; in those cases, the normal handling is to let the exception reach the most outer block of your code that displays to the user that an unpredictable error has occurred and the application can't do nothing to continue. It's a a fatal condition, so the only thing you can do is to print it to the logs or showing it to the user in the user interface. In those cases, catching the exception is wrong, because, after catching the exception you need to manually stop the program to avoid further damages; so it could be better to let some kind of exception "hit the fan" :)
For those reasons there are some exceptions that are Unchecked also in the JRE: OutOfMemoryError (unrecoverable), NullPointerException (it's a bug that needs to be fixed), ArrayIndexOutOfBoundsException (another bug example), and so on.
I personally think that also SQLException should be unchecked, since it denotes a bug in the program, or a connection problem to the database. But there are many examples where you get exception that you really don't have any clue in how to manage (RemoteException).
The best way to handle exceptions are: if you can recover or manage the exception, handle it. Otherwise let the exception pass out; somebody else will need to handle. If you are the last "somebody else" and you don't know how to handle an exception, just display it (log or display in the UI).
you do not need to declare unchecked exceptions in a throws clause; but you must declare checked exceptions;
RuntimeException and Error, and all of their subclasses (IllegalArgumentException, StackOverflowError etc), are unckecked exceptions; the fact that RuntimeException is unchecked, unlike other Throwable subclasses, is by design;
there is no such thing as "compile time exceptions".
More generally, it is considered that unchecked exceptions are thrown in the event of either JVM errors or programmer errors. One famous such exception is NullPointerException, often abbreviated as NPE, which is a subclass of RuntimeException, and therefore unchecked.
Another very crucial difference between unchecked exceptions and checked exceptions is that within a try-catch block, if you want to catch unchecked exceptions, you must catch them explicitly.
Final note: if you have exception classes E1 and E2 and E2 extends E1, then catching and/or throwing E1 also catches/throws E2. This stands for both checked and unchecked exceptions. This has an implication on catch blocks: if you do differentiate between catching E2 and E1, you must catch E2 first.
For instance:
// IllegalArgumentException is unchecked, no need to declare it
public void illegal()
{
throw new IllegalArgumentException("meh");
}
// IOException is a checked exception, it must be declared
public void ioerror()
throws IOException
{
throw new IOException("meh");
}
// Sample code using illegal(): if you want to catch IllegalArgumentException,
// you must do so explicitly. Not catching it is not considered an error
public void f()
{
try {
illegal();
} catch (IllegalArgumentException e) { // Explicit catch!
doSomething();
}
}
I hope this makes things clearer...
No. All the exceptions happen at runtime. Checked exceptions are exceptions that force the caller to handle them or declare them. They are usually intended to signal recoverable errors, which are not caused by a programmer error (like a file not being there, or a network connectivity problem). Runtime exceptions are usually intended to signal non-recoverable errors. They don't force the caller to handle or declare them. And many of them indeed signal programming errors (like NullPointerException).
Because that's how the JLS define an unchecked exception: an exception that is or extends RuntimeException, which itself extends Exception. Using a single inheritance root allows handlong every possible exception in a single catch clause.
Regarding your example: yes, the throws clause is mandatory, since IOException is a checked exception and that the code inside the method is susceptible to throw one.
The compiler only makes sure a method can't throw a checked exception if it didn't declare it. It is a general belief that such checking by compiler should be done for the exceptions whose occurrence is outside programmer's control, such as the examples you cite (database connectivity, files missing, etc.). Unchecked exceptions are "not supposed to happen", so the compiler doesn't force you to declare them.
As for simulating IOException or any other, it is trivial:
throw new IOException();
In your example the prompt method may throw an IOException, that's why it needs to declare it. This has nothing to do with how you handle the exception at the point you call the method.
RuntimeException is a subclass of Exception to make it convenient to catch all exceptions with one catch Exception clause. This could have been designed differently; Java's exception class hierarchy is a mess.
If you dont put throws clause in here then this error will occur
ThrowsDemo.java:5: unreported exception java.io.IOException; must be caught or d
eclared to be thrown
return (char) System.in.read();
so throws clause in necessary.
Five example of checked exception and unchecked exception.
Unchecked Exception
-- NullPointerException
-- ArrayIndexOutofBound
-- IllegalArgument Exception
-- ClassCastException
-- IllegalStateException
-- ConcurrentModificationException
Checked Exception Five Example
-- FileNotFoundException
-- ParseException
-- ClassNotFoundException
-- CloneNotSupportException
-- SQLException
Checked and unchecked exceptions
There are two types of exceptions: checked exceptions and unchecked exceptions.
The main difference between checked and unchecked exception is that the checked exceptions are checked at compile-time while unchecked exceptions are checked at runtime.
Please read this article to get a clear idea.
More Details
Use checked exceptions when the client code can take some useful recovery action based on information in exception. Use unchecked exception when client code cannot do anything. For example, convert your SQLException into another checked exception if the client code can recover from it and convert your SQLException into an unchecked (i.e. RuntimeException) exception, if the client code cannot do anything about it.

Why does this method that throws an exception not have to be in a try catch block when invoked?

I invoke a method that throws exceptions, but I don't need to place this method inside a try catch block in static void main(String args[]), even though this tutorial says I should get an error. Why is this? Below is my code and a link to the tutorial. I played around with the second example in the tutorial.
https://beginnersbook.com/2013/04/java-throws/?unapproved=133049&moderation-hash=486e9de11daa2c67068e84cdacd88794#comment-133049
public class Sample2 {
static void myMethod() throws ArithmeticException, NullPointerException {
System.out.println("myMethod has been successfully called");
throw new ArithmeticException("Arithmetic Expression has been thrown");
}
public static void main(String args[]) {
myMethod();
}
}
The tutorial has a subtle mistake: although it clearly states that there is one kind of exceptions that does not need to be caught, it fails to notice that the exceptions thrown in their own examples are unchecked, i.e. of the Runtime variety:
On the other hand unchecked exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for handling checked exceptions.
Replace ArithmeticException with an exception that you derive directly from Exception to see the error.
When talking about Exceptions in Java, only 2 main types are invoked: checked exceptions and unchecked exceptions.
The checked exceptions are checked in compile time: if you don't handle a checked exception (by using a try/catch block for example or the throws key word), the compiler will raise an error, in other words, it won't let you build your program, this is why you should always handle all the checked exceptions.
The unchecked exceptions are checked in runtime: your compiler will not raise an error if you don't handle these type of exceptions.
Now the question is: how can i distinguish between these two types when i am coding ?
You should first keep in mind that every exception in java should inherits from the "Exception" class.
Now, there is a simple way you can tell a unchecked exception from a checked one: any exception class that inherits from "RuntimeException" is considered an unchecked exception, and any class that inherits from "Exception" but not "RuntimeException" is considered is a checked exception.
In your case, the method you're invoking throws a ArithmeticException and a NullPointerException. But this two exceptions inherits from the "RuntimeException". So, according to the rule written above, these 2 exceptions are unchecked exceptions, and that's why you had no need to handle it when invoking your method myMethod().

Need a better explanation for try/catch/throw/throws exception handing in Java

I am a little unsure about the difference between the try/catch, throw and throws in Java and every website seems to have an inhuman way of explaining it, I have tried the Oracle website but I just could not understand their explanation, is this correct?
Try/catch
With try catch, I want to try a piece of code and if something goes wrong do this.
Throw
With throw, I am throwing an error because I want to?
So if I wanted to validate a users age, say all people over 20 and the user does not meet the requirements, I would throw an error?
Throws
With Throws I am throwing an error but something else handles the exception? Would this be another method/class?
Try / Catch
try
{
// try to do some actions
}
catch(SomeExceptionType exception)
{
// if the above actions throw a SomeExceptionType, do these actions
}
Throw
Correct. We're explicitly throwing an exception. You may do this if, for example, the caller of a method has violated your method's contract. Perhaps an argument cannot be negative.
In this situation, the best way to deal with this is to throw an exception which stops what we're doing and allows callers further up the stack to deal with the problem:
/** Do a thing. myInt must be positive */
void someMethod(Integer myInt)
{
if (myInt < 0)
{
throw new IllegalArgumentException("Can't be negative");
}
// do something
}
void myCaller()
{
someMethod( 1); // won't throw
someMethod(-1); // will throw
}
Throws
throws is used as a keyword when dealing with checked exceptions. It's a way of letting callers know what checked exceptions they can expect they may have to deal with.
Those methods can decide to deal with the problem (i.e. a try-catch) or can themselves declare the same exception type to be thrown to propagate the exception up to their caller (and so on and so on)
You forget a important point : in Java all exceptions are not handled by the compiler in the same way.
The compiler ensures only that the checked exceptions be handled.
These exceptions don't inherit from RuntimeException but from Exception (directly or indirectly).
So whatever you throw in your code or a method of a third class declares throwing a checked exception, you have to explicitly handle it.
And there you have two ways :
catching the exception
letting the exception be propagated to the caller
try/catch addresses the first way while specifying the throws modifier in the method declaration addresses the second.
For no RunTimeExceptions, you don't have this constraint as the compiler doesn't force you to handle it. You may handle them if you want to.

Throwing custom exceptions in Java versus built in exceptions

I'm a little confused because I want to be able to throw a custom exception in Java. To do this inside a function, I have to add throws MyException to the header of the function.
And then anything that calls that function in turn must add throws MyException or have a try-catch block. But why is this?
For example, when creating a Stack in java and calling the pop function, I don't have to have a try-catch and yet the pop method in Java throws a NoSuchElementException (or w/e it is) if there isn't an element on the stack.
NoSuchElementException is a RuntimeException (un-checked exception) and we don't need to handle or declare RuntimeExceptionS, thus the compiler wont complain, but instead throw it at runtime.
In the case of checked exceptions i.e., all the exceptions which are not subtypes of RuntimeException, the compiler will check for a suitable catch clause, enabling the program to continue its course of execution, after performing the operations within the catch; to do this, you need to handle them using try/catch blocks or declare them using the throws clause - delegating the responsibility of handling the exception higher up the call chain. If your custom exception is not a RuntimeException rules of checked exceptions apply to your custom exception as well.
Checked exceptions ---> Forced by the compiler to handle or propagate
Un-checked exceptions ---> Not checked by the compiler thus appears at runtime
Java has so called checked exceptions and unchecked exceptions. A checked exception must be declared in method signature, an unchecked exception does not need to be declared.
If you want to define an unchecked exception yourself derive it from RuntimeException insted of Exception.
you are supposed to throw or try-catch all checked Exceptions , its not required for RunTimeException and exception that you are talking about is a RuntimeException
See my answer to this question.
As a general rule of thumb, when deciding whether or not to create a custom exception class, I try and use the built-in exception classes as much as possible, where it makes sense to do so, e.g. IllegalArgumentException, etc.
Here is an example of how to create a custom RuntimeException, which, as you have discovered, will not require a try/catch/finally block, or a throws clause.
public class MyRuntimeException extends RuntimeException {
public MyRuntimeException() {
super();
}
public MyRuntimeException(String message) {
super(message);
}
}
public class MyClass {
public void go(int val) {
if(val <= 0) throw new MyRuntimeException("Val must be greater than 0.");
}
}

can't java unchecked exceptions be handled using try/catch block?

In a tutorial I found that Unchecked Exception can't be handled by your code i.e. we can't use try/catch block and the examples are exceptions like ArrayIndexOutOfBoundsException, NullPointerException. But these exceptions can be handled using try/catch block. I think i am not clear about the concept !!
Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with UncheckedException?
The only difference between checked and unchecked exceptions is that checked ones have to be either caught or declared in the method signature using throws, whereas with unchecked ones this is optional.
Unchecked Exception can't be handled by your code i.e. we can't use try/catch block
Sure we can - but we don't have to.
Also i think throw keyword can be used only with try/catch block.can throw Keyword be used with Unchecked Exception?
Note that there are two keywords:
throw explicitly throws an exception object you created. throw new NullPointerException(); works perfectly fine, though explicitly creating that particular exception is uncommon and most would consider it bad style.
throws declares that a method may throw that exception. With unchecked exceptions this is optional, but can be useful to document the fact (again, one would normally not declared throws NullPointerException because that is pretty much a given).
All the unchecked exceptions can be treated in the same way as the checked ones - if you want, you can let them pass by declaring that the method throws them:
public void m() throws RuntimeException {}
Or you can catch them:
public void m() {
try {
// some code
} catch (RuntimeException re) {
// do something
}
}
It should be noticed, the class RuntimeException acts as a catch-all for the unchecked exceptions (since all the unchecked exceptions extend from it), much in the same way that the Exception class is the catch-all for checked exceptions.
As has been mentioned before, the only real difference is that for checked exceptions you have to handle them (by letting them pass or catching them) and the compiler will make sure of it - on the other hand, the handling of unchecked exceptions is optional.
It all boils down to the expected usage of each exception type - you're supposed do be able to recover from checked exceptions (or at least do something about them, when they occur), whilst for unchecked exceptions, there might not be a reasonable way to recover from them. This of course, is a bit subjective.
They can be handled, but you don't have to. If you don't handle them, they will propagate and climb up the calling methods stack, until one of them catches it. If none does, the program will crash.
Usually, the bottom line is that if a client can reasonably be expected to recover from an exception, then it should be a checked exception. If a client cannot do anything to recover from the exception, then it's ok to have it as an unchecked exception.
Also, checked exceptions are useful to document an API that you expect to be used by 3rd-parties. When they know your method can throw a specific exception, they will code accordingly and handle the case. If you only use unchecked exceptions, all bets are off.
A common pattern (some people don't like it, but in some cases it's ok when you know what you're doing) is to wrap thrown checked exceptions into unchecked ones.
try {
... code that can throw CheckedException ...
} catch (CheckedException oopsSomethingBadHappened) {
throw new RuntimeException("Something bad happened!", oopsSomethingBadHappened);
}
An easy way to think about the difference is to think the checking refers to the compile. If an exception is a checked exception, the compiler will check that your code either throws the exception or handles it in a try/catch block at compile-time. For unchecked exceptions, the compiler won't do such a check. You can handle checked/unchecked exceptions the same way (with try/catch/throws), the difference just lies in the checks the compiler performs. This post has a decent example.
In addition to Guillaume:
unchecked exceptions are usually programming errors, which should not happen at all if implemented correctly (index out of bound, null pointer, class cast,...) and therefore the caller/ user usually cannot do anything about them.
checked exceptions are thrown because it was outside of the control of the programmer (network not availabe, filesystem not available, concurrent modifications such as duplicated primary key,...)
errors are usually thrown by the JVM and the application usually has to stop (out of memory, stack overflow,...)
Yes, you can throw unchecked exceptions with throw. And yes, you can catch unchecked exceptions in a catch block.
Yes you can handle the unchecked exception but not compulsory. Actually it depends on application developer. Below is the possible reason where i think required to handle even unchecked exception.
If your application is large where many developers are calling each other API. It is better to handle the unchecked exception otherwise at the end your program will crash which stop the other functionality. So even the simple NullPointerException can stop your program working.
Imagine you have one scheduler which processing the user data and which is in million size and for the bad data you only want to print the log not to stop working for other good data. In that case if you have not handle the exception one bad data can stop your program
yes we can handle Runtime Exception, plz check below code
public class Demo {
static void m1() {
int a[]=new int [5];
try {
a[12]=2;
}catch(Exception e) {
}
}
public static void main(String[] args) {
m1();
try {
String s=null;
System.out.println(s.length());
}catch(Exception e) {
}
System.out.println("hello world");
}
}

Categories