This is the original exception code
public class NoValueForParametarException extends Exception {
private Exception nestedException;
private int errorCode;
public NoValueForParametarException(String message) {
super(message);
}
public NoValueForParametarException(Exception ex,String message) {
super(message);
this.nestedException = ex;
}
public NoValueForParametarException(String message, int errorCode) {
super(message);
this.setErrorCode(errorCode);
}
public Exception getNestedException() {
return this.nestedException;
}
public void setNestedException(Exception nestedException) {
this.nestedException = nestedException;
}
public int getErrorCode() {
return this.errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String toString() {
StringBuffer errorMsg = new StringBuffer();
errorMsg.append("[" + super.getMessage() + "]:");
errorMsg.append((this.nestedException != null) ? ("\n[Nested exception]:" + this.nestedException):"");
return errorMsg.toString();
}
}
and this is the new one
public class NoValueForParametarWebServiceException extends NoValueForParametarException {
public NoValueForParametarWebServiceException(String message) {
super(message);
}
public NoValueForParametarWebServiceException(Exception ex,String message) {
super(message);
this.setNestedException(ex);
}
public NoValueForParametarWebServiceException(String message, int errorCode) {
super(message);
this.setErrorCode(errorCode);
}
public String toString() {
StringBuffer errorMsg = new StringBuffer();
errorMsg.append(super.getMessage());
errorMsg.append((this.getNestedException() != null) ? ("\n[Nested exception]:" + this.getNestedException()):"");
return errorMsg.toString();
}
}
All I need is to change the part of the toString() method so instead of errorMsg.append("[" + super.getMessage() + "]:"); I have errorMsg.append(super.getMessage());. The problem appears when, in a method, the original is thrown because the catch block set to NoValueForParametarWebServiceException doesn't catch the original. I know I could catch the original and just re-throw the new one (which would also be satisfying), but I was wondering if there is another way.
EDIT: It seems what I need is unclear, so to be more clear:
The program throws NoValueForParametarException. I want to catch it but use the toString() method of NoValueForParametarWebServiceException (that is the sole reason of creating the new class) because I need the output format of the new version without changing the old.
I don't see any reason to subclass your first exception. Also, if you get rid of the nestedException instance variable and use java.lang.Throwable's cause instead, you don't have to mess with overriding toString and you can delete most of this code.
The problem appears when, in a method,
the original is thrown because the
catch block set to
'NoValueForParametarWebServiceException'
doesn't catch the original. I know I
could catch the original and just
re-throw the new one (which would also
be satisfying)
You don't need to re throw child exception.
Just catch parent exception in this case.
try{
//your code
}catch(NoValueForParametarException e){
//whatever handling you need to do. suppose you call toString() method
System.out.println(e.toString());
}
In above case catch block will be executed if any of your exceptions are thrown
(NoValueForParametarException or NoValueForParametarWebServiceException).
And depending upon which exception is thrown its toString() method will be called. (Simple inheritance rule) i.e.
NoValueForParametarException is
thrown toString defined in
NoValueForParametarException class
will be called for instance.
And if
NoValueForParametarWebServiceException
is thrown then overriden toString
method from
NoValueForParametarWebServiceException
will be called.
Some tutorials related to exceptions:
http://download.oracle.com/javase/tutorial/essential/exceptions/index.html
http://tutorials.jenkov.com/java-exception-handling/index.html
Hope this helps.
Related
I got an issue to handle NoSuchElementException and NullPointerEception.
I tried to handle NoSuchElementException error from this code:
public Item shop(ItemShopParam itemShopParam) {
String orderNumber = itemShopParam.getOrderNumber();
Shipment shipment = shipmentService.findByNumber(orderNumber);
Item item = findBySku(shipment.getId(), itemShopParam.getItemSku());
Job job = item.getShipment().getJobs().stream().filter(j -> j.getType().equals(Job.Type.RANGER)).findFirst().get();
checkJobState(job);
private void checkJobState(Job job) {
if (job.getState() == Job.State.INITIAL)
throw new JobNotStartedException();
if (job.getState() == Job.State.FINISHED)
throw new JobAlreadyFinishedException();
}
by replace get() with Optional().orElse(null). But, it returned another error exception NullPointerException. I know why this happened because checkJobState check null value of job.
The enum state:
public enum State {
INITIAL(0),
STARTED(1),
LAST_ITEM_PICKED(2),
FINALIZING(3),
ACCEPTED(4),
DELIVERING(5),
FOUND_ADDRESS(6),
FINISHED(7),
FAILED(8);
What is the best practice to avoid NoSuchElementException without return NullPointerException?
You can use Optional.isPresent() check:
Optional<Job> maybeJob = item.getShipment().getJobs().stream().filter(j -> j.getType().equals(Job.Type.RANGER)).findFirst();
if(maybeJob.isPresent()) {
checkJobState(job);
}
or even better an ifPresent():
Optional<Job> maybeJob = item.getShipment().getJobs().stream().filter(j -> j.getType().equals(Job.Type.RANGER)).findFirst().ifPresent(job -> checkJobState(job));
you can put the instructions to get the job from itemShopParam in a java Function, in this way you can easy test it.
Then use try catch to get any unexpected behaviour and specialise it in your exception inside a catch block.
The exception fired could be checked, if extends Throwable or Runtime if you wants manage it optionally.
//FUNCTION CLASS
class FromItemShopParamToJob implements Function<ItemShopParam,Item>
{
#Override
public Item apply(ItemShopParam itemShopParam) {
Item i=new Item();
//instructions to get job
return i;
}
}
class FromItemToJob implements Function<Item,Job> {
#Override
public Job apply(Item item) {
Job j=new Job();
//instructions to get job
return j;
}
}
//YOUR EXCEPTION CLASS
public class JobNotFoundException extends RuntimeException{
public JobNotFoundException(String message) {
super(message);
}
}
//YOUR METHOD
public void getJobFromItemShop(ItemShopParam param){
try {
Item item = new FromItemShopParamToJob().apply(param);
Job j=new FromItemToJob().apply(item);
} catch (Exception e){
System.out.print(e);
throw new JobNotFoundException(e.toString());
}
}
I want to save a method in an Enum, but Class.getDeclaredMethod is throwing NoSuchMethodException, so how can I handle it?
My Code:
public enum Card {
OPENPRISON(false, Cards.class.getDeclaredMethod("", Player.class));
private boolean isInstant;
private Method method;
private Card(boolean isInstant, Method method){
this.method = method;
this.isInstant = isInstant;
}
public boolean isInstant() {
return isInstant;
}
public void run(Player p){
}
}
and OPENPRISON is the problem
An immediate technical issue is that you're not providing a method name in your call to getDeclaredMethod():
OPENPRISON(false, Cards.class.getDeclaredMethod("", Player.class));
A larger issue is why you need to use reflection at all.
An enum value is a constant. What can you do with reflection that you could not as easily do with a static method? Or with a method outside the enum?
Well your code throws a checked exception, so you could use a method:
OPENPRISON(false, foo());
private static Method foo() {
try {
return Cards.class.getDeclaredMethod("", Player.class);
} catch (NoSuchMethodException e) {
return null;
}
}
Of course, the question remains if you cannot solve your problem without reflection - most likely it is possible.
I have a JUnit test class, which I'm new to making. I also trying to learn how to make my own exception classes. I have been creating a BigInt class, and one of the constructors takes in Strings. This bit of code is looping through an array, and its supposed to be checking if the character at each position is an integer. Right now there is an error that says "Unreachable catch block for BigIntFormatException. This exception is never thrown from the try statement body" Any ideas for why?
String[] s = { " - - 1424", "+ + 14324", "a142432", "1432 3413",
"+242134.32421", "", " \n", "\t ++" };
for (int i = 0; i < s.length; i++) {
try {
BigInt b = new BigInt(s[i]);
assertFalse(true);
} catch (BigIntFormatException e) {
assertTrue(true);
}
}
So far this is what my BigIntFormatException class just looks like, so any help with this part would be appreciated too.
public class BigIntFormatException extends Exception {
public BigIntFormatException() {
super();
}
public BigIntFormatException(String message) {
super(message);
}
}
Simply put, this compilation failure is quite clear: neither the constructor to BigInt nor the assertion declare that they are going to throw BigIntFormatException.
Since Exception is the class of checked exceptions (meaning that you do have to wrap them in a try-catch block), you must declare them to be thrown in your constructor of BigInt.
Here's the way you would do that.
public BigInt(String str) throws BigIntFormatException {
// logic
}
You need to throw the exception in your BigInt class
if(/*error condition*/) {
throw new BigIntFormatException("your message");
}
I am trying to call a custom catch expression
String value1 = side1_tb.getText();
String value2 = side2_tb.getText();
String value3 = side3_tb.getText();
try
{
result_lbl.setText(
actual_triangle.Triangle(
Double.parseDouble(value1),
Double.parseDouble(value2),
Double.parseDouble(value3)));
}
catch (NumberFormatException exe)
{
}
So from the above code you can see that there are three textboxes values are being assigned to a string variables and then I implemented a try and catch method with 'Numberformatexception' but in the place of 'Numberformatexception' I want to implement a custom exception and this exception will be declared in another class lets call this class EXCEPTIONclass.java and in here I want to create an exception if String values are not being able to parse to double values, which I am trying to achieve in the above code.
Not really sure how to extend the exception class and then declare a new exception.
You could do it as follows:
public class MyCustomException extends Exception
{
// To keep compiler happy about Exception being serializable.
// Note: This should carry meaningful value when these exceptions are going
// to be serialized
public static final long serialVersionUID = 1L;
public MyCustomException(String message, Throwable t)
{
super(message, t);
}
// Other constructors of interest from the super classes.
}
In your catch block, you would wrap the NumberFormatException as follows:
catch (NumberFormatException nfe)
{
throw new MyCustomException("<Your message>", nfe);
}
Just create your exception class deriving it from Throwable ( for checked exception ) or RuntimeException ( if you like it to be unchecked ) and throw it from your catch clause.
So I'm given this code and I have to create an Exception and then use a Try/Catch Block to catch it. I've already made the Exception, at the bottom of the code. But I've never used a Try/Catch Block before and am not sure how to implement it.
The Exception is if a rank that isn't listed under the enum is entered. I need to use a toString with the caught exception as well, but I'm pretty sure I can figure that one out.
package pracapp4;
import java.util.Scanner;
public class Staff extends Employee
{
enum Title
{
DEPARTMENT_HEAD, DIRECTOR, DEAN, VICE_CHANCELLOR, CHANCELLOR
}
private Title title;
public Staff()
{
super();
title = Title.DEPARTMENT_HEAD;
}
public Staff(String firstName, String lastName, int salary, Title title)
{
super(firstName, lastName, salary);
this.title = title;
}
#Override
public String toString()
{
return super.toString() + "\n\tTitle: " + title;
}
#Override
public void display()
{
System.out.println("<<Staff>>" + this);
}
#Override
public void input(Scanner in)
{
super.input(in);
if (in.hasNext())
{
this.title = Enum.valueOf(Title.class, in.next());
}
}
class InvalidRankException extends Exception
{
public InvalidRankException()
{
super ("Unknown Rank Name: ");
}
}
}
You don't need that exception. The moment you add your Title enum as the type you pass into the Staff constructor it's impossible to provide a value that's not in the enum. You'll never get an invalid title. That's the whole point of enum.
UPDATE: A little code review is an order here.
Your default constructor is rather odd. You can be department head without a name or salary? A call to "this" is appropriate here, and better default values are in order.
Whole numbers only for salary - OK. No units? USD? Euro?
Can salary be negative? Does that make sense? (Note to self: Don't work there.)
Why do you need both toString and display? What is display overriding? I'd recommend ditching display and sticking with toString.
Your input method makes no sense whatsoever.
Why is that Exception an inner class?
try/catch are used to catch exceptions thrown by methods inside the try clause. If the methods inside the try does not throw any exceptions then the try/catch will not makes sense.
Right now you made your exception but there is no method that throws your exception.
This is simple example on how to use exceptions:
public class myTest
{
public void myMethod() throws InvalidRankException
{
//Logic here
if(something_is_wrong)
{
throw new InvalidRankException("Invalid Rank on myMethod due ...");
}
}
class InvalidRankException extends Exception
{
public InvalidRankException()
{
super ("Unknown Rank Name: ");
}
}
Now, whenever you run MyTest.myMethod() the compiler will require a try/catch surrounding that call.
MyTest test = new MyTest();
try
{
test.myMethod();
}
catch(InvalidRankException ex)
{
//Something went wrong
}
Not exactly sure what you're trying to do, but try-catch blocks work like this:
try{
throw new Exception("Example exception");
}
catch(Exception e){
System.out.println( "Exception caught: " + e.getMessage() );
}
You'll also have to modify the method that you are trying so that it throws the Exception you're looking for:
public void doSomething(String blah) throws Exception
Catching an exception is as simple as:
try{
//Some code that throws MyExceptionClass
}catch(MyException e){
//Some code that handles the exception e
}
Throwing an exception is as simple as:
throw new MyException(some, parameters, of, your choice);
If your exception doesn't descend from RuntimeException then you must declare the the method throws it:
public void myExceptionCausingMethod() throws MyException{
//Method code
}
The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code.
public void input(Scanner in) throws InvalidRankException {
super.input(in);
if (in.hasNext()) {
try {
title = Enum.valueOf(Title.class, in.next());
} catch(InvalidRankException ire) {
//You've hit the exception, code in here how to handle the situation
}
}
}
There's two issues here:
Enum won't return an invalid rank/title
InvalidRankException doesn't test for anything to cause it to fire.