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());
}
}
}
Related
Okay guys I've been trying to figure this out for the past day or so. My homework assignment has me creating both Unchecked and Checked Exceptions. The checked exceptions I believe I get basically they must be handled before compiling (With try & catch or throwing it to the next thing that calls it. For unchecked exceptions I don't understand how custom ones work. They are caught at runtime and don't necessarily need to be thrown or encased with try & catch but if they're custom how does the IDE or whatever know what to look for? Example: One of my custom Unchecked files is supposed to trigger if the user adds a pokemon but the party is full, but how do I tell the IDE that that's what needs to happen? My Exception file looks like:
public class PartyIsFullException extends RuntimeException {
public PartyIsFullException() {
super();
}
public PartyIsFullException(String message) {
super(message);
}
}
and then I want to implement it in this method, but idk how to do it. I realize now I can't throw them because the user won't be expecting them and therefore won't try to catch them.
public void addToParty(String name) throws PartyIsFullException {
boolean exists = false;
for (int i = 0; i < 152; i++) {
exists = (name.equals(pokedex[i]));
}
if (exists) {
throw new PokemonAlreadyExistsException();
} else {
if (partyPos < 6) {
party[partyPos] = name;
partyPos++;
} else {
throw new PartyIsFullException();
}
}
}
I realize now I can't throw them because the user won't be expecting them and therefore won't try to catch them.
You can throw them!
In a real project, it should be clearly documented.
/*
* #throws PartyIsFullException if isPartyFull() would return true
*/
public void addToParty(String name) throws PartyIsFullException {...}
Usually an unchecked exception is used for a situation where the client of the method is avoiding the exceptional condition themselves e.g.:
if(theParty.isPartyFull()) {
// tell the user the party is full
// and they can't add more Pokemon
} else {
theParty.addToParty(thePokemon);
}
And thus they shouldn't have to explicitly catch it because they are already handling that circumstance.
If the exception is thrown and there is not a try-catch outside, it will throw all the way up to terminate the thread. (For a small program with just main, this means the program crashes.)
Although you don't know if a certain custom unchecked exception could or not be thrown from a certain method you still can catch it (or it's superclass Exception). Having custom exception against provided by Java could add some useful details specific for your exceptional case (i.e. exception name should be meaningful so that it makes it easier to read your logs).
Custom (unchecked) exception creation and it's content could also be tuned to suit your particular need. E.g. PartyIsFullException constructor could take a Party object and format it's state into a String.
In case you don't need to facilitate your unchecked exception creation/presentation it's OK to go with RuntimeException assuming you provide a descriptive message.
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();
}
}
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.
( patience requested as i'm new to programming )
when you add the phrase throws ABCexception in method declaration like this
public static void main(String[] args) throws ABCException {
}
does it mean that the you expect the method could generate an ABC exception and by writing throws ABCException ... when this exception occurs .. this exception will be caught and some prewritten code in java language will be executed corresponding to the ABCException. ?
thanks
throws declares that the method may throw the exception so the code that invoke this method must be prepare for it.
Being prepared for exception means that the code may catch the exception or re-throw it up.
Consider the constructor new FileInputStream(File pFile) which will create a FileInputStream from a File object. Since the file may not exist or not readable the constructor will throw FileNotFoundException (as declared).
So any code that call this constructor will either catch or rethrow it.
Catching it, the code will taking care of that exception by themself while rethrowing it, the code will let its caller take care of it.
Consider the following two codes:
Code 1: Catch -> Take care of it
public String readTextFile(File pFile) {
try {
FileInputStream FIO = new FileInputStream(pFile);
... // Do the reading and return
} catch (FileNotFoundException E) {
System.err.println("The file is not found");
}
}
Code 2: Throw -> Let the caller take care of ot
public String readTextFile(File pFile) throws FileNotFoundException {
FileInputStream FIO = new FileInputStream(pFile);
... // Do the reading and return
}
So the caller of readTextFile will have to catch or rethrow it too.
This mechanism ensures that someone have to take care of the exception in someway.
I hope I help.
The thows ABCException statement, before the function definition starts in earnest is just to indicate that this function may throw such an exception.
The actual throwing of the exception would happen within the code of the function. With code like the following (note the lack of an 's' at the end of "throw")
throw new ABCException();
The exceptions are then passed on "up" through the chain of the program logic that called this function this function, until one these "catches" the exception and deals with it. In case the exception "bubbles back" all the to the main() function, and if said exception isn't caught there either, a default handler deals with it, typically by printing out the exception to stderr/stdout and halting.
The way this exception could be caught would be with a try-catch construct, as in:
try
{
// do some stuff if needed
xy = fct(); // this fct may throw the ABCExeption...
// do more stuff as well
}
catch (ABCException e)
{
// for debugging you can do this
e.printStackTrace();
// otherwise you could deal with this exception as desired.
}
In re-reading the question, I noted that the function which is declared with throws ABCException and that is a bit odd, because main is the first method in the chain of function calls, meaning that there is nothing before main() which could catch an exception (other than the default exception handler of the Java Runtime, which wouldn't do anything specific for ABCException; it would just "dump it" to the console (or elsewhere for GUI-based apps) like any other exception.
I am getting an error in NetBeans saying I must throw an SQLException in this method:
private void displayCustomerInfo(java.awt.event.ActionEvent evt)
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}
This method is created by NetBeans so it is not allowing me to edit the signature and throw the exception. This is why I created the getCustomerInfo() method. This method does throw the exception, because it uses a method to retrieve information from a database about a customer.
public String getCustomerInfo(int cid) throws SQLException
{
Customer c = proc.getCustomer(cid);
// get info
return "info";
}
The getCustomer method also throws the exception and proc.java compiles.
The exact error is
unreported exception java.sql.SQLException; must be caught or declared to be thrown
In general, if your code needs to throw a type of Exception that the signature doesn't support, and you have no control over the interface, you can catch and rethrow as a type the interface does support. If your interface doesn't declare ANY checked exceptions, you can always throw a RuntimeException:
private void displayCustomerInfo(java.awt.event.ActionEven evt)
{
try
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}
catch (SQLException ex)
{
throw new RuntimeException(ex); // maybe create a new exception type?
}
}
You almost definitely want to create a new Exception type that extends RuntimeException, and have your client code catch that exception. Otherwise, you run the risk of catching ANY RuntimeException, including NullPointerException, ArrayIndexOutOfBoundsException, etc., which your client code probably can't handle.
Read the error message again, it gives you two choices.
You must either declare the exception as thrown (which you cannot do) or catch the exception. Try the 2nd choice.
You need to put a try/catch block around your call to getCustomerInfo(), like so:
private void displayCustomerInfo(java.awt.event.ActionEvent evt)
{
int custID = Integer.parseInt(customerID.getText());
try {
String info = getCustomerInfo(custID);
} catch (SQLException sqle) {
// Do something with the exception
}
results.setText(info);
}
A couple good options for handling the exception might be: logging the exception and the details used to get it, or using it as a signal to retry the connection request. Alternatively, as Outlaw Programmer shows, you could re-throw the Exception as a RuntimeException of some kind, which removes the requirement of checking.
It does not say you must throw it. It says you can catch it. So use a try/catch block and handle it.
try {
...
}
catch (SQLException e) {
System.out.println("Exception happened! Abort! Abort!");
e.printMessage(); //Not sure if this is the correct method name
}
NetBeans generated components have un-modifiable code, and I'm guessing that it is generated as a part of the gui builder. I'd ask if this was the case, but I can't comment yet. If you select a generated object in the GUI editor, on the right there is a tab "code" that can be used to modify the grayed out area of the code.
Here:
I've come across this problem... been puzzled for the past 2 days.. then I open the source (.java file) with sublime, change the code, save, and it works wonders... I'm laughing when I see this works... think outside the box really works...