Throw an Exception Object Creation - java

Is an exception object created when a catch statement is implemented?
For example, catch (ArithmeticException someObject)
Does this object not have to explicitly be created as an instance?

There are two things creating Instance of the Exception the second throwing the Exception
creating an Instance of The Exception looks like creating any instance of Class for example NullPointerException npe = new NullPointerException(); at this moment we didn't do any thing more than creating an instance, some times we didn't create the instance of Exception by ourselves as we will see
Throwing Exception after creating instance of Exception class we throw it, you can throw the Exception by yourself or the JVM will do
try
{
int a = 10/0;
}catch(ArithmeticException a)
{
RuntimeException exception = new RuntimeException("a very bad error occured", a);
throw exception;
}
when Java tried to compute 10/0 it encounter an arithmetic error so the JVM creates an instance of class ArithmeticException and throws this created instance which you catch it in your catch clause, where we create an instance of class RuntimeException it's just an object and then throw it using throw

You are creating an object. But you aren't creating an instance of it.
The Exception object instance is created when someone throws it.
try {
Foo foo = null;
foo.dofoo();
} catch(NullPointerException e) {
// ...
}
In this particular case, the JVM created the NullPointerException object instance that you are handling in the catch block.
In few words imagine that in some part of the JVM there's something like:
if (obj == null) {
throw new NullPointerException();
}
Do not take the previous code sample serious. It's an exemplification of Exception throwing.

Related

When exception occur, what is responsibility of exception class?

When exception occur in try block, catch block will handle it. So what is responsibility of exception class? I found in exception class in Java and only saw some function to provide infomation about exception(???). What is exception class do when exception occur . And if i want to write my own MyException extend Exception, what method i should write in exception class to handle my exception
What is exception class do when exception occur
Nothing.
if i want to write my own MyException extend Exception, what method i write in exception class to handle my exception
You don't need to implement anything, but you may want to have constructor to set message and store some relevant information.
When some code encounters a "problem", it may create an Exception object that describes the problem and throw it to the calling code to say "things didn't go as planned for reason X".
It is the up to the calling code to handle the exception (with a try/catch block) and act appropriately. The exception doesn't say or care about what should be done next.
If you are in a situation where you want to describe a specific issue more precisely that what a "standard" exception allows, you can create your own exception. Say you sell products that can only be sold to people between 20 and 40:
throw new AgeLimitException(clientAge, 20, 40);
And the client code:
try {
buyProduct();
} catch (AgeLimitException e) {
showMessage("Your age is " + e.getAge() + " but you must be between " + e.minAge()
+ " and " + e.maxAge() + " to buy this product");
}
As you can see, the role of the AgeLimitException is simply to give information about the problem that occurred.
We create User-Defined-Exception class to handle the upcoming exceptions , when a exception occur then it will create the Exception class object ,where we have declared what to do when do do next ,so our program flow or process going on didn't break .
Exception class is a type of Throwable. It only gives you an exception(an issue that breaks your flow of execution) information.
Throwable is also a class & superclass(parent) of all Error & Exception. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.
Custom Exception: Java provides the facility to create our own exceptions which are basically derived classes of Exception.
A Class that represents a use-defined exception
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
A Class that uses above MyException
public class Main
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException("My own exception");
}
catch (MyException ex)
{
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage());
}
}
}

Difference between "throw new Exception" and "new Exception"?

I am interested to know best practice to use throw new Exception() and new Exception(). In case of using new Exception(), I have seen that code moves to next statement instead of throwing exception.
But I am told that we should use new Exception() to throw RuntimeException.
Can anyone throw some light on this ?
new Exception() means create an instance (same as creating new Integer(...))
but no exception will happen until you throw it...
Consider following snippet:
public static void main(String[] args) throws Exception {
foo(1);
foo2(1);
}
private static void foo2(final int number) throws Exception {
Exception ex;
if (number < 0) {
ex = new Exception("No negative number please!");
// throw ex; //nothing happens until you throw it
}
}
private static void foo(final int number) throws Exception {
if (number < 0) {
throw new Exception("No negative number please!");
}
}
the method foo() will THROW an exception if the parameter is negative but
the method foo2() will create an instance of exception if the parameter is negative
Exception e = new Exception ();
Just creates a new Exception, which you could later throw. Using
throw e;
Whereas
throw new Exception()
Creates and throws the exception in one line
To create and throw a runtime exception
throw new RuntimeException()
new Exception() means you are creating a new instance of Exception type. Which means you are just instantiating an object similar to others like new String("abc"). You would do this when you are about to throw an exception of type Exception in next few lines of code execution.
While when you say throw new Exception() this means you are saying move the program control to caller and don't execute the further statements after this throw statement.
You would do this in a situation where you find that there is no way to move ahead and execute further and hence let caller know that i can't handle this case and if you know how to handle this case, please do so.
There is no best practice as such as you are comparing oranges with apples. But remember when throwing an exception, you always throw a meaningful exception like IO has where if file is not present it throws FileNotFoundException instead of its parent IOException.

Return only if no Exception is thrown

I'm implementing a fixed sized Queue in java which uses a constant size ArrayList as underlying container, where my front() method is supposed to return front element of Queue .
public T front(){
try{
if(isEmpty())
throw new Exception("Queue is Empty- can't return Front element.");
return arrayList.get(frontIndex);
}catch (Exception e){
System.out.println(e);
}
}
By coding in above way , I want front() to return a value only if no Exception is thrown ,however as expected compiler show me "Missing return statement." So , is there any way I can make the function return only if no Exception is thrown.
Since you are catching the exception in the code the compiler shows that missing return statement error.
You can implement the function Like this :
public T front() throws Exception {
if(isEmpty()) {
throw new Exception("Queue is Empty- can't return Front element.");
}
return arrayList.get(frontIndex);
}
and finally handle the exception at calling function/client
I want front() to return a value only if no Exception is thrown
Rhetorical question: What do you want to return if an Exception is thrown?
Here is the problem. You have declared front() as returning something (an instance of T). That means that there are two relevant ways1 to terminate a call to front():
It can terminate normally by returning something that conforms to the type T.
It can terminate abnormally by throwing an unchecked exception.
You can't return "nothing", because front() has to return a value.
You can't throw a checked exception (like Exception) because front() is not declared as throwing any exceptions.
So what can you do?
You can change the method signature so that SomeException is thrown, where SomeException descends from Exception. (Throwing Exception is a really bad idea ...)
You can change throw new Exception to throw new SomeException, where SomeException is descended from RuntimeException.
You can return null assuming that T is a reference type. (It will be if T is a type parameter.)
1 - Actually, there are a couple of other ways, but they are not useful in this context. For example, you could call System.exit(int) and terminate the JVM. (And there are ways of structuring the code so that you don't need a (redundant) return or throw following the exit call. Hint: infinite loops don't need to return.)
Why do you use the exception at all if you are catching it afterwards? You have to either return T or throw an exception. But the method doesn't throw an exception since you are catching it. Is it not easier to do just that:
public T front() throws SomeException{ // if SomeException is checked you need to declare it
if(isEmpty())
throw new SomeException("Queue is Empty- can't return Front element.");
return arrayList.get(frontIndex);
}
You should also use a more specific exception, not Exception.
this "example" shows a possibility when u can throw an exception and return value
private boolean throwExReturnValue() throws NullPointerException {
try {
throw new NullPointerException("HAHA");
}
finally {
return true;
}
}
private void ExceptionHanler() {
boolean myEx;
try {
myEx = throwExReturnValue();
/** code here will still execute & myEx will have value = true */
} catch (Exception ex) {
/** will execute or not (depending on VM) even we throwed an exception */
}
/** code will still execute */
}
EDIT:
i tried this with two different VM and to my surprise one is throwing Exception second is skipping the catch block and execute code so it's depending on VM implementation

Exception type created class used in another

I can't seem to find a way to fix this. I have a class called CardException which extends Exception. The only code it has is:
public class CardException extends Exception{
String erro;
public CartaoException(String erro){
this.erro = erro;
}
}
Now I have another class with a method in which I want to throw an Exception if the condition is false:
public void changePin(int pin, int newPin){
try{
if(pin == getPin()){
setPin(newPin);
}
} catch (CardException e){
System.out.println(e.getMessage());
}
}
but I'm getting an error at "catch (CardException e)" saying:
"Unreachable catch block for CardException. This exception is never thrown from the try statement body" and I have no idea why.
The point is to create a class called CardException of Exception type, with a constructor that receives an error message as argument. Then, on my other class, I need to create that method changePin which receives the old pin and a new pin and, if the old pin doesn't match the one already saved, it has to throw and exception with a message: "Invalid pin".
Java compiler is intelligent enough to determine whether the statements inside try blocks are prone to a checked exception or not. As no statement in your try block seems to cause CardException, hence compiler complains.
Just for the sake of testing, if you add throws clause with CardException to either of your getPin/setPin method, then compiler will not complain as those methods can throw the exception in catch block.
Since CardException extends Exception, not RuntimeException, it is considered a checked exception. What that means is that all methods from which the exception is thrown must declare the exception in their throws declaration clause.
Because of this requirement Java compilers can check if a code block throws a particular checked exception or not:
If there is a throws block inside the code body that throws this exception or one of its subclasses, the catch is valid
If any of the functions called inside the code body is declared as throwing the exception or one of its subclasses, the catch is valid
Otherwise, the catch is invalid, and the compiler issues an error.
You would need to catch this exception if getPin or setPin threw it. In this case, however, the functions would need to add a throws CardException to their declarations.

Is it necessary to use "throws" whenever we use "throw"?

Assuming that the Exception we are throwing is checked, is it compulsory to add throws in a method declaration whenever we use throw inside the method?
Any checked exception (e.g., one which does not extend RuntimeException) that might escape a method needs to be declared in the method signature. For example:
public static void mightThrow(String s) throws NumberFormatException {
// ...
int x = Integer.parseInt(s);
// ...
}
Even though we do not throw any exceptions directly, Integer.parseInt() might throw a checked NumberFormatException. Since we call that method, and we do not catch the potential exception, then our method must also declare the exeception in its throws signature.
This does not necessarily mean that every method that throws (or might throw) a checked exception must declare throws in its signature. If the thrown exception is always caught within that method, it need not be added to the signature. For example:
public static Integer tryParseInteger(final String s) {
try {
return Integer.parseInt(s);
}
catch (NumberFormatException ignored) {
return null;
}
}
In this example, we will always catch any NumberFormatException that might be thrown by Integer.parseInt() and prevent it from bubbling up the stack, so we do not need to declare it in our tryParseInteger() method.
Unchecked exceptions never need to be declared:
public static void unsupported() {
throw new UnsupportedOperationException(
"The specified operation is not supported."
);
}
Here, because UnsupportedOperationException derives from the unchecked RuntimeException, it does not need to be declared.
No, since you may want to throw a exception but handle it in the same place, aka method
The Throws simply let javac know that this method might cause this kind of exception. It is not always necessary. It's useful when you know that a specific method can throw some sort of exception.
Generally speaking, Java is exception-strict, so you have to specific what types of exceptions a method throws. Note that you can use inheritance to simplify your methods' signatures. E.g., you can declare your method as throws IOException, and within its implementation throw any type of IOException you want such as FileNotFoundExeption, InteruptedIOException, etc.
One exception (no pun intended) to this rule are RuntimeExceptions (such as OutOfMemoryError or UnsupportedOperationException) which can be thrown without having to declare them.
Differences:
1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException("not able to open connection").
2) throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method
signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:
private static boolean shutdown() {
throw new UnsupportedOperationException("Not yet implemented");
}
as in below method shutdown should return boolean but having throw in place compiler understand that this method will always throw exception .
3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside method or static initializer block provided sufficient exception handling as shown in example.
static{
try {
throw new Exception("Not able to initialized");
} catch (Exception ex) {
Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
4) throw keyword can also be used to break a switch statement without using break keyword.
int number = 5;
switch(number){
case 1:
throw new RuntimeException("Exception number 1");
case 2:
throw new RuntimeException("Exception number 2");
}

Categories

Resources