This question already has answers here:
How to define custom exception class in Java, the easiest way?
(8 answers)
Closed 8 years ago.
I need to change the return message of the method getMessage() ,
for instance, i have an ArithmeticException, and when I write:
try{c=a/0;}
catch(ArithmeticException excep){System.out.println( excep.getMessage() );}
and I execut this code I have: / by zero.
So, I wanted to change this result by overwriting the getMesage method.
I have created a new class called MyException that inherits from ArithmeticExceprtion and I override the methode getMessage, and after that I have changed the type of the exception in my last code from ArithmeticException to my new name class MyException:
public class MyException extends ArithmeticException{
#override
public String getMessage(){
retun "new code message";}
}
and I have changed the first code, I have wrotten:
try{c=a/0;}
catch(MyException excep){System.out.println( excep.getMessage() );}
and when I have executed this code, I had the same error's message as if I didn't catch the exception:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at main.test.main(Test.java:33)
So, my question is: how can I change the message of the methode getMessage() ?
You have extended the ArithmeticException with a new class called MyException. But the statement c = a / 0; still throws ArithmeticException but never MyException itself, so your catch clause is not reached.
Note that normally you shouldn't catch runtime (unchecked) exceptions like ArithmeticException since it denotes a programming error. Also note that for checked exceptions, the compiler shows an error telling you that the statement would never throw that kind of exception, but in this case, MyException is an unchecked exception so the compiler is fine with it.
In your particular scenario, you cannot change the message of the exception since it will always be an ArithmeticException. But you can always print whatever message you want in the catch clause. Or you can wrap the statement in a method and let that method throw the subclass exception:
public void foo() throws MyException {
try {
c = a / 0;
} catch (ArithmeticException excep) {
// handle excep
throw new MyException();
}
}
Related
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());
}
}
}
This question already has answers here:
Why is throwing a checked exception type allowed in this case?
(3 answers)
Closed 6 years ago.
Consider the following code:
static void main(String[] args) {
try {
} catch (Exception e) {
throw e;
}
}
This code compiles without having to add throws Exception to the method signature. (It behaves similarly with Throwable in place of Exception, too).
I understand why it can be run safely, in that Exception can't actually be thrown in the try block, so a checked exception cannot be thrown; I'm interested to know where this behaviour is specified.
It's not simply that the throw e is never reached: the following code also compiles:
static void stillCompilesWithThrownUncheckedException() {
try {
throw new NullPointerException();
} catch (Exception e) {
throw e;
}
}
But if you throw a checked exception, it doesn't compile, as I expect:
static void doesNotCompileWithThrownCheckedException() {
try {
throw new Exception();
} catch (Exception e) {
throw e; // error: unreported exception Exception; must be caught or declared to be thrown
}
}
In JLS Sec 11.2.2, it says:
A throw statement (§14.18) whose thrown expression has static type E and is not a final or effectively final exception parameter can throw E or any exception class that the thrown expression can throw.
My interpretation of this statement is that throw e can throw Exception, because the static type of e is Exception. And then, in JLS Sec 11.2.3:
It is a compile-time error if a method or constructor body can throw some exception class E when E is a checked exception class and E is not a subclass of some class declared in the throws clause of the method or constructor.
But it's not a compile-time error in the first two cases. Where is this behavior described in the language spec?
Edit: having marked it a dupe, I was going to ask the follow-up question: why isn't throw e; considered unreachable in the first example.
The answer was much easier to find in JLS Sec 14.21:
A catch block C is reachable iff both of the following are true:
Either the type of C's parameter is an unchecked exception type or Exception or a superclass of Exception, or some expression or throw statement in the try block is reachable and can throw a checked exception whose type is assignable to the type of C's parameter. (An expression is reachable iff the innermost statement containing it is reachable.)
See §15.6 for normal and abrupt completion of expressions.
There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
Both of these are true (it's of type Exception, and there's no earlier catch block), so it's "reachable". I guess the effort of calling out an empty try block as a special case was too great for such a marginally-useful construct.
I believe the very next paragraph of section 11.2.2 answers the question:
A throw statement whose thrown expression is a final or effectively final exception parameter of a catch clause C can throw an exception class E iff:
E is an exception class that the try block of the try statement which declares C can throw; and
…
So, throw e; “can throw” only exceptions which the corresponding try-block “can throw,” where the latter is defined by the actual statements in the try-block.
Obviously an empty try-block does not qualify as a “can throw” section for any exception class. Your second example “can throw” NullPointerException, and since the catch-block “can throw” only the exception that the try-block “can throw,” the catch-block too can throw only the unchecked NullPointerException.
Your third example’s try-block “can throw” java.lang.Exception itself, therefore the catch-block “can throw” java.lang.Exception, so java.lang.Exception must be caught or declared to be thrown.
This question already has answers here:
Exception handling : throw, throws and Throwable
(8 answers)
Closed 6 years ago.
I am confused to get a clear understanding of when throw is used and throws is used. Kindly provide me an example to show the difference.
Also, I tried the below code:
package AccessModifiers;
//import java.io.IOException;
public class ThrowExceptions {
int QAAutoLevel;
int QAExp;
void QAAutomationHiring(int grade)
{
if (grade<5)
throw new ArithmeticException("Not professionally Qualified");
else
System.out.println("Ready to be test");
}
void QAExperience(int x,int grade)
{
QAAutomationHiring(grade);
}
void checkThrowsExep(int a,int b) throws ArithmeticException
{
try{
int result=a/b;
System.out.println("Result is :"+result);
}
catch(Exception e)
{
System.out.println("The error messgae is: "+ e.getMessage());
}
}
public static void main(String args[])
{
ThrowExceptions t=new ThrowExceptions();
//t.QAAutomationHiring(8);
t.QAExperience(2,8);
t.QAExperience(4,2);
t.checkThrowsExep(5, 0);
}
}
In the above code, when I run the program, the line- 't.checkThrowsExp' in main function is not reached. I studied that throw and throws are used to catch the exception and continue with the program execution. But here the execution stops and not proceeding to the next set of statements. Please share your comments.
throws is used to tell people that
Warning: this method/constructor has a high chance of throwing XXXException and YYYException! Please make sure you handle them!
Example:
The Thread.sleep method is declared as:
public static native void sleep(long millis) throws InterruptedException;
As you can see, the throws keyword tells people that sleep is very likely to throw an InterruptedException. Because of this, you must surround the method call with try-catch or mark the caller method with throws InterruptedException. The exceptions after the throws keyword are usually "checked" exceptions which are caused by invalid conditions in areas outside the immediate control of the program, like invalid user inputs, database problems etc.
Please note that it is possible for a method marked with throws XXXExcepion to never throw XXXException.
throw, on the other hand, actually throws the exception. It can be used like
throw new RuntimeException("Something went wrong!");
And whenever code execution reaches this statement, an exception will be thrown no matter what, and the method returns.
In short, throw actually does the throwing, and throws is only saying that an exception will likely be thrown (which in fact, be wrong).
Throw actually returns the exception whereas throws is a sign to the compiler, that this method could return an exception.
In your code above the exception ArithmeticException will be created and returned, if the grade is lower than 5, which is the case in your second call of QAExperience.
As the calling method called the method, which returned the exception, is not insede a catch block it will also just stop its execution and return to the main method. As the main method also does not catch the exception it will just like the others stop its execution and return the exception. This is the reason, why t.checkThrowsExp will not be executed.
I am confused about the behaviour of the CustomExceptions in below program.If Line2 is commented and Line1 is not then program works well,but if Line1 is commented and Line2 is not then compile time error comes as "Unreachable catch block for CustomChecked.This exception is never thrown from the try statement body" for Line3.Please help me why this comple time exception comes only for the unChecked Exception?.
try
{
if(true)
{
throw new CustomChecked("Checked Exception");// Line1
// throw new CustomUnChecked("Un-Checked Exception");// Line2
}
}
catch(CustomChecked ex) //Line3
{
System.out.println(ex.getMessage());
}
catch(CustomUnChecked ex)
{
System.out.println(ex.getMessage());
}
Exceptions :
class CustomChecked extends Exception
{
public CustomChecked(String msg) {
super(msg);
}
}
class CustomUnChecked extends RuntimeException
{
public CustomUnChecked(String msg) {
super(msg);
}
}
CustomUnChecked is a RuntimeException which is unchecked meaning that the complier doesn't check who can/do throw that exception. Compiler assumes that every object/method/code block can throw any type of RuntimeException and so that you can always check for this type of exceptions in your check statements.
On the other hand CustomChecked is checked, meaning that the compiler checks for all methods and code blocks that can throw it. So you can only catch the checked exception if you know (at a complie time) that you invoke a method/code that throws the exception inside the try block.
So to sum up - your compilator informs you, that the catch you have in line 3 is not needed (and so should be removed), because there is no way that somebody will throw CustomCheckedException inside the try statement. As CustomUnCheckedException is not checked by compiler (it is runtime, assumed to be thrown unexpected anywere), the check statement for it can stay.
The part of the Java Spec that is applicable here is 11.2.3. It reads
It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.
Notice that this clause is restricted to 'checked' exceptions. Unchecked exceptions, by definition of being 'unchecked' do not have these checks applied to them. Hence the difference in behavior that you are seeing.
The compiler does not check if you catch RuntimeExceptions, but it does check that you catch Exceptions. Thats why you get an error if you try to catch a non-existant checked exception (if its not in the throws clause, it shouldnt exist, since its a checked exception), and no error if you are catching a RuntimeException (which can happen even through you didnt put it in the throws clause, a NullPointerException for example).
So, in short, CheckedExceptions MUST be declared in the throws clause and MUST be catched.
Unchecked exceptions CAN be catched, but the compiler has no way of knowing the if code throws an unchecked exception, so it wont give you an error if you check on it or not.
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.