Handling Exceptions without try-catch - java

Suppose we have a method (not main) and it has this piece of code in it's body:
if (a > b) {
throw new IllegalArgumentException("Fail!");
}
Is it equivalent to try-catch way of handling an exception or including the throws in the signature?

There are 2 kinds of exceptions in Java: checked exceptions and unchecked exceptions.
When a checked exception is thrown, the method signature must add a throw declaration. The calling code should embrace it in a try-catch.
When an unchecked exception is thrown, the method signature should not add the throw declaration. The calling code is not obliged to embrace it in a try-catch.
How to distinguish between these two kinds of exceptions? An unchecked exception does extend RuntimeException.
IllegalArgumentException belongs to the unchecked exceptions.

If you throw a Exception you need to catch it or you need to add throws to the method.
But I think you are confused as that is a RuntimeException you are throwing. RuntimeException need not be handled by try catch blocks. So it is not = to having a try catch as it doesn't need one...
So you are really asking the difference between a checked vs unchecked exception.

It's better to include a try catch and handle what you are going to do when that exception comes up.
But the way you have it written, it'll just cascade up until it comes across a try-catch or something that takes care of the exception.

This is nowhere equivalent to try-catch handling or throws.
Here, your method is throwing an IllegalArgumentException, which has to be handled in the method definition with throws as throws IllegalArgumentException or the caller of this particular method has to use try-catch to handle the IllegalArgumentException thrown by this method.

Related

Why doesn't android studio always warn about calling methods which throw exceptions?

In some cases, android studio lets me call a method which throws an exception, without a try/catch. Why is that? How can I enforce it to always warn me about it?
Two kinds of exceptions
Checked Exceptions are those that are inherited from the Exceptionclass, you will be warned
Unchecked Exceptions are inherited from RuntimeException, calling a method that throws them will never show a compiler warning, but as the name suggest "just" mess it up at runtime ;-)
Here a short list of common exceptions, to help you weary restless searching fellows out ...
UNCHECKED exceptions
StackOverflowError
RuntimeException
ArrayIndexOutOfBoundsException
ClassCastException
IllegalArgumentException
IllegalStateException
NullPointerException
NumberFormatException
AssertionError
ExceptionInInitializerError
NoClassDefFoundError
CHECKED exceptions
Exception
ClassNotFoundException
CloneNotSupportedException
FileNotFoundException
ParseException
InstantiationException
InterruptedException
IOException
NoSuchFieldException
NoSuchMethodException
The problem seems to be about checked/unchecked Exceptions, as #RubioRic and #Altoyyr said. I didn't know about the difference.
For the exception you can handle, use
try{
//your business logic
}catch(Exception e) {
//Err handling logic
}
For the exception you cannot handle, do not use an empty try/catch block, but use throws exception instead. Let the custom error handler you wrote to handle it from outer class etc.
//business logic which you know it will throw certain kind of exception
throw XException("your err descrption");
The last case is you don't even know what happened, please fix the code according to the exception/ err trace, it is a bug where business logic should handle well.
Please read about the error handling in java throught this link:
http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html

When do I have to surround with try/catch?

I have some piece of code:
public static void a() throws NumberFormatException {
return;
}
public static void b() throws InterruptedException{
return;
}
public static void main(String[] args) {
a();
b();
}
And Eclipse says that I have to surround try/catch to function call b(), but I do not have to do that with a() call. Why? How to make function make to surround with try and catch when is called?
Because InterruptedException is a checked exception and NumberFormatException is an unchecked expcetion.
For checked exception, compiler forces you to either surround them with try-catch block or declare them with throws, while for unchecked exceptions try-catch block is not compulsory.
As function a() throws NumberFormatException (unchecked exception) compiler do not force you to surround the function call with try-catch.
As function b() throws InterruptedException (checked exception) compiler forces you to either surround the function call with try-catch or declare them with throws.
NumberFormatException is not a checked Exception(i.e because it has java.lang.RuntimeException as its base class), which means that the developer is not forced to handle(its the developer's choice whether to handle it or not) when the developer chooses not to handle the exception and if the exception occurs, it will be handled by the JVM.
Where as InterruptedException (i.e because it has java.lang.Exception as its base class) is a checked exception which means that the developer has to handle it every time either by using a try-catch block or by declaring the exception in the Throws clause.
Take a look at this example.
This is because NumberFormatException extends RuntimeException - i.e. it is unchecked exception. While InterruptedException is checked exception - it should be catched in try...catch block, or you should add throws to main() method.
because NumberFormatException() is unchecked exception InterruptedException is checked, you have to surroud checked exceptions with try-catch, but you dont have to try-catch checked - every method would have try-catch then.
NumberFormatException is a RuntimeException -> unchecked
InterruptedException is a checked Exception
I found the Java Tutorial quite useful to learn about Java and its APIs, and in fact, I still use it from time to time:
http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
http://docs.oracle.com/javase/tutorial/
public class InterruptedException
extends Exception
Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception.
but for the first case it will not ask NumberFormatException is an unchecked expcetion.
All Exception that extends RuntimeException do not imply an explicit try-catch block. They are called Unchecked. Those exception were theoretically reserved to unrecoverable runtime errors thrown by VM. However they are now commonly used as lot's of people agree to say the Checked exceptions mechanism is a bad design concept.
You will commonly use Unchecked when your program cannot recover from the error and let them propagate to a transverse layer exception handling that will be in charge to properly log and / or display the error to user.
Checked exception are commonly used in cases where the caller will be expected to handle the error, because it is able to recover from it or will trigger specific behavior.
The Keyword throws declares that a method may throw that exception. While checked exceptions have to be handled with unchecked exceptions this is optional. In your case a throws a NumberFormatException which is derived from RuntimeException which is according to the definition an unchecked exception, see Section 11.2: Compile-Time Checking of Exceptions:
The unchecked exceptions classes are the class RuntimeException and
its subclasses, and the class Error and its subclasses. All other
exception classes are checked exception classes.
And according to the definition the InterruptedException which class b throws is a checked exceptions (must be caught in a try-catch block).
There are two ways in Java to handle exceptions -
1. surround try/catch
2. propagate exeption
you use try/catch block if you want to handle this exception locally. Basically, within the try block is a code that has a potential of throwing an exception.
but you use throws SomeException in the method signature if you want this possible exception to be handled by the calling method... this calling method can also propagate this exception further up... should all methods never try/catch this exception, it will be thrown by the Java Virtual Machine at execution time

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.");
}
}

Methods that throw an exception that do not require catching

Sorry if this is a very basic question
As for my understanding if you have a method that throws an exception, you are required to catch it (or throw it) whenever you will be using that method.
However some methods that throw an exception do not require me to catch it like:
int num = Long.parseInt(sampleString);
Can anybody shed some light please?
There are two types of exceptions in Java: checked and unchecked. The former needs to be catched while the latter does not. An unchecked Exception is a class that extends either RuntimeException, Error, or one of their subclasses.
Long#parseLong throws a NumberFormatException which IS-A RuntimeException. Thus, it's an unchecked exception and does not need to be caught.
References:
Unchecked Exceptions -- The Controversy
There are exceptions which extend from RuntimeException. These are known as unchecked exceptions and they do not have to be declared in your method signatures. Generally, these are reserved for things which have really gone wrong.
There are 2 types of exceptions in Java. Checked and unchecked. Unchecked exceptions don't need to be caught. A good example of an unchecked exception is NullPointerException; you can see that if developers needed to catch this exception code would be ridiculously complicated. It would be lunacy. The exception that parseInt throws in an unchecked exception.
Those are subclasses of the RuntimeException. RuntimeExceptions and its subclasses don't need to be caught. They are called unchecked exceptions.

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