Handling throws with an ArithmaticException Constructor - java

Question: Write a method called addTwoPositive that takes two int parameters, and if either value is not positive, throw an ArithmeticException, passing the String "Non-positive integers sent!" to the constructor of the exception. If the values are both positive, then return the sum of them.
I am confused as to how to handling this exception through the ArithmeticException constructor. Here is my code:
package IfnotPos;
public class IfNotPositive extends ArithmeticException{
public static void main(String[] args) throws ArithmeticException{
IfNotPositive pos = new IfNotPositive();
System.out.println(pos.addTwoPositive(-3,2));
}
public int addTwoPositive(int plus, int plus1) throws ArithmeticException{
if(plus < 0 || plus1 < 0){
throw new ArithmeticException("Non-positive integers sent!");
}
else{
return plus + plus1;
}
}
public ArithmeticException(String string) {
return string;
}
}
I get an error of "return type for the method is missing" and if I change it to string or anything else, it will obviously stop being a constructor. Any help handling this exception will be greatly appreciated.

First of all you don't need to extend ArithmeticException class. You are not creating a custom exception, but writing a program to throw ArithmeticException (note this resides in java.lang) if a condition is not met.
Problem with your code is that constructor you have defined is never meant to be there and is not correct, hence the compiling issue.
public ArithmeticException(String string) {
return string;
}
Just remove this constructor and you are good to go.

I don't understand why you want to create constructor for ArithmeticException in your code?
public ArithmeticException(String string) {
return string;
}
You don't write a constructor like this. This is syntax exception complaining about the above method. This constructor is unnecessary. Remove this your code will work perfect. You should see below exception running your program...
Exception in thread "main" java.lang.ArithmeticException: Non-positive
integers sent! at
com.code.samples.IfNotPositive.addTwoPositive(IfNotPositive.java:14)
at com.code.samples.IfNotPositive.main(IfNotPositive.java:8)

From Providing Constructors for Your Classes
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
I get an error of "return type for the method is missing"
You are getting this error because public ArithmeticException(String string) line in your code.
You can't add constructor of any other class inside another class, so Java treating public ArithmeticException(String string) as function rather constructor.
And as you know for method you need to have return type mendetry
You don't have to extend, ArithmeticException class. See below code:
public class IfNotPositive{
public static void main(String[] args) throws ArithmeticException{
IfNotPositive pos = new IfNotPositive();
System.out.println(pos.addTwoPositive(-3,2));
}
public int addTwoPositive(int plus, int plus1) throws ArithmeticException{
if(plus < 0 || plus1 < 0){
throw new ArithmeticException("Non-positive integers sent!");
}
else{
return plus + plus1;
}
}
}
Q: throw an ArithmeticException, passing the String "Non-positive integers sent!"
It means throw ArithmeticException with detail message "Non-positive integers sent!"
So for that you can use public ArithmeticException(String s) Constructor.
Constructs an ArithmeticException with the specified detail message.
Ex:
throw new ArithmeticException("Non-positive integers sent!");

Related

getConstructor() return a constructor that is not implemented

I'm learning some of the reflection features in Java and I got a strange problem testing the getConstructor() function with this Class.
public class IntegerSequence {
private Integer[] elements;
private int size;
private int MAX_SIZE = 100;
public IntegerSequence() {
elements = new Integer[MAX_SIZE];
size = 0;
System.out.println("Hello Guys");
}
}
The function returns a valid constructor but the "Hello Guys" message is never printed.
Furthermore, If I delete the constructor of IntegerSequence, it also return a valid constructor and doesn't throw any exception, even if there is no one anymore in IntegerSequence class.
I read that getConstructor() only returns a constructor coded in the class and not one made automatically by Java so I'm a bit lost.
Here is the code that use the function and it's output:
public void invokeDefaultConstructor(Class c){
Constructor build = null;
try {
build = c.getConstructor();
} catch (NoSuchMethodException e) {
System.out.println(e);
e.printStackTrace();
}
System.out.println(build.toString());
System.out.println(build.getName());
}
console Output:
public generics.IntegerSequence()
generics.IntegerSequence
Do you know what could cause that kind of behaviour ?
The function return a valid constructor but the "Hello Guys" message is never printed.
That's expected, since you never call the constructor anywhere. You only get the constructor from the class.
I read that getConstructor() only return a constructor coded in the class and not one made automatically by Java
I don't know where you read that. The javadoc certainly doesn't say that.

Exception is never thrown in the corresponding try block

I have this method:
public int addInt(int x, int y){
try{
if(x<1 || y<1){
throw new InvalidValueExeption();
}
} catch(InvalidValueExeption i){
System.out.println(i);
}
return x+y;
}
InvalidValueExeption is a custom exception. So I wanted to test this:
#Test
public void test(){
AddClass a = new AddClass();
boolean thrown = false;
try{
a.addInt(-2, 3);
} catch(InvalidValueException e){
thrown=true;
}
assertTrue(thrown);
}
I can't run this test, because it says Exception exception.InvalidValueException is never thrown in the corresponding try block.
What am I doing wrong?
Your addInt() method doesn't throw InvalidValueException (*). Inside the method, you do throw it, but you catch it before it can "leave" your method. So, for the outside world, there is no InvalidValueException coming from your method.
Then, correctly the compiler tells you that there's no point in catching the InvalidValueException.
So, instead of immediately catching the exception inside your method, declare the method to throw InvalidValueException:
public int addInt(int x, int y) throws InvalidValueException {
if (x < 1 || y < 1) {
throw new InvalidValueException();
}
return x + y;
}
Rationale:
Exceptions are meant to tell the caller (**) of some method that it couldn't fulfill its task, i.e. your addInt() method is designed to add only positive numbers. And if someone tries it with a number below 1, the method answers with the exception instead of returning a value, thus saying: "Hey, something went wrong, so I can't give you an answer (and the problem description is [the exception with its message and so on])."
( * ) I assume, the missing "c" is just a typo, and you don't have two different exception classes.
( ** ) That's important. I'm not talking about System.out.println(), as that's telling something to the user, not the caller.
If InvalidValueExeption is a checked exception then the compiler will complain because addInt is not declared to throw InvalidValueExeption.
If InvalidValueExeption is not a checked exception then the test will fail because addInt swallows the InvalidValueExeption.
There's also a possible typo in your question: addInt() throws InvalidValueExeption whereas test() tries to catch InvalidValueException. In the former case exception is spelled "Exeption", in the latter case it is spelled "Exception", note the missing "c".
The following approach will work:
public int addInt(int x, int y) {
if (x < 1 || y < 1) {
throw new InvalidValueException();
}
return x + y;
}
#Test(expected = InvalidValueException.class)
public void test(){
AddClass a = new AddClass();
a.addInt(-2, 3);
}
First of i think your InvalidValueExeption is a subtype of RuntimeException.
RuntimeException and its subclasses are unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or
constructor's throws clause if they can be thrown by the execution of
the method or constructor and propagate outside the method or
constructor boundary.
So if you need to indicate that you throw an InvalidValueExeption or inherit Exception instead.
Here the exception is declared on your method and thrown :
public int addInt(int x, int y) throws InvalidValueExeption {
try {
//..
throw new InvalidValueExeption();
} catch (InvalidValueExeption e) {
// do some logging the throw back at you
throw e;
}
}

Unreported Exception/this() need to be first statement

i m writing a very simple java class and i faced a weird problem, i know there are many simple way to resolve it but now i have a doubt
public class Frazione {
private int num;
private int den;
public Frazione(int x, int y) throws FrazioneException {
if (y == 0) {
throw new FrazioneException();
}
num = x;
den = y;
}
/*public Frazione(int x){ THAT'S HOW IT SHOULD BE BASED
ON THE EXCERCISE BUT IT WON'T
COMPILE BECAUSE THIS ISN'T THE
FIRST STATEMENT
try{
this(x,1);
}catch(FrazioneException e){
System.err.print("errore: "+e);
}
}*/
/*public Frazione(int x){
this(x,1); IF I TRY THIS WAY I'LL BE IN
AN UNREPORTED EXCEPTION PROBLEM
}*/
public int getNum() {
return num;
}
public int getDen() {
return den;
}
}
there's a way to use try and catch with this() statement?
Yes, this doesn't work. You'd have to fulfill two contradictory requirements:
the this call has to be the first statement
the this call has to be in a try..catch statement.
So this can't be solved.
What you could do:
If you want to throw a checked exception in the constructor, throw it also in the other one. But that doesn't make real sense, because it will never been thrown, because you never pass y=0
Convert FrazioneException to a runtime exception and remove throws.
Try to solve your requirement without throwing an exception from the constructor (I usually avoid that because it often causes too much trouble. Like the one you have)
If there are multiple constructors and you are using this keyword within a constructor to call another constructor, the invocation of another constructor (this()) must be the first line of the constructor.

Correct way of returning an error code in a method

I have this method in a "Point" class:
public Point sumPoints(Point p) {
if(dimension != p.getDimension())
throw new RuntimeException("Wrong dimensions.");
Double[] coord = new Double[dimension];
for(int i = 0; i < dimension; i++)
coord[i] = coordinates[i] + p.getCoord(i);
Point P = new Point(coord);
return P;
The idea is that points can be n-dimensional, so I should check that the dimensions of the points match before trying to add them up. The thing is that in the case that they don't match, I can't return a specific value (-1 for example, as I did in C), because the return type is Point.
What should I do in these cases? Is the RuntimeExeption an okay practice?
In short the answer to your question is yes. Exceptions is the accepted way to handle errors. There are a lot of Exceptions that are more specific that inherit from RuntimeException though.IllegalArgumentException comes to mind. Also you can write your own exceptions that inherit from a RuntimeException. And then of course there is a mammoth of a discussion about which Exception to use Unchecked (inheriting from RuntimeException) or checked (inheriting from Exception). Just type in Google "runtimeexception vs exception" and you will get a screenfull of links to keep you buisy :). Here is just one Example: difference between java.lang.RuntimeException and java.lang.Exception. There is no clear cut answer for that. You will have to choose on your own.
Exception handling is a much more elegant way to implement error handling in Java for a number of reasons.
Error codes
Returning error codes works well in C especially because of the ability to pass pointers as function parameters in C: In this way, you can e.g. create a new object inside the function and "return" it via the pointer passed to the function and let the function actually return a proper error code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int create_message_str(char *p_message, const size_t p_message_len)
{
int result = -1;
const char message[] = "Hello, world!";
if (NULL != p_message && strlen(message) <= p_message_len)
{
strcpy(p_message, message);
result = 0;
}
return result;
}
int main(int argc, char **argv)
{
int result = EXIT_FAILURE;
const size_t p_message_len = 13;
char *p_message = malloc(p_message_len * sizeof(char));
if (create_message_str(p_message, p_message_len) == 0)
{
printf("%s\n", p_message);
result = EXIT_SUCCESS;
}
else
{
fprintf(stderr, "%s\n", "Could not copy string to pointer memory.");
}
free(p_message);
return result;
}
In Java, however, you'd have to create an instance of e.g. some sort of mutable Supplier-like object for holding the reference to the object which would be referenced by the pointer in the C function:
public class ReferenceSwapper {
private static class MutableSupplier<T> implements Supplier<T> {
private T supplied;
public MutableSupplier(final T supplied) {
this.supplied = supplied;
}
#Override
public T get() {
return supplied;
}
public void set(final T supplied) {
this.supplied = supplied;
}
}
public static void main(final String[] args) {
final MutableSupplier<String> firstSupplier = new MutableSupplier<String>("foo");
final MutableSupplier<String> secondSupplier = new MutableSupplier<String>("bar");
System.out.println("Before reference swap: " + firstSupplier.get() + secondSupplier.get());
swapSupplied(firstSupplier, secondSupplier);
System.out.println("After reference swap: " + firstSupplier.get() + secondSupplier.get());
}
private static <T> void swapSupplied(final MutableSupplier<T> firstSupplier,
final MutableSupplier<T> secondSupplier) {
final T firstSupplied = firstSupplier.get();
final T secondSupplied = secondSupplier.get();
firstSupplier.set(secondSupplied);
secondSupplier.set(firstSupplied);
}
}
This code prints out:
Before reference swap: foobar
After reference swap: barfoo
As you can see, this is ridiculously complicated in Java due to its pass-by-value semantics.
Exceptions
However, Java offers a much higher-level way of defining error-handling behavior: Exceptions. Although some people debate if the idea of exceptions are a good thing or not and exception handling is really just fancy conditional logic, they are part of the Java language and can work well for reporting exceptional (i.e. erroneous) states.
As Andy Turner already mentioned, throwing an IllegalArgumentException would be the most natural way of reporting an error regarding the method's particular arguments which you shouldn't (normally) have to catch and handle: You'd be assuming that the people using sumPoints(Point p) are smart enough to pass the correct arguments or at least to suffer a program halt if they aren't so. However, if you do expect that this is a common occurrence is at least an occurrence which cannot be avoided purely through judicious programming (e.g. if the data is read from disk and might somehow get corrupted or not be available), then it might be better to throw a caught exception in order to force the calling method to handle the case where this happens.
the thing with exceptions in java is that you can code your own class that extends from Exception to use it in a class which you treat all kind of possible exceptions that could encounter your program then you just throw it.
example :
public class Erreur extends Exception{
String message;
public Erreur(String message){
this.message=message;
}
public String getMessage(){ return message;}
}
Then
public class Calcule {
public static double division(double x, double y) throws Erreur{
double r=0;
Erreur erre=new Erreur("can't divide by zero");
if(y==0) throw (erre);
else r=(x/y);
return r;
}
}

How can I throw a general exception in Java?

Consider this simple program. The program has two files:
File Vehicle.java
class Vehicle {
private int speed = 0;
private int maxSpeed = 100;
public int getSpeed()
{
return speed;
}
public int getMaxSpeed()
{
return maxSpeed;
}
public void speedUp(int increment)
{
if(speed + increment > maxSpeed){
// Throw exception
}else{
speed += increment;
}
}
public void speedDown(int decrement)
{
if(speed - decrement < 0){
// Throw exception
}else{
speed -= decrement;
}
}
}
File HelloWorld.java
public class HelloWorld {
/**
* #param args
*/
public static void main(String[] args) {
Vehicle v1 = new Vehicle();
Vehicle v2 = new Vehicle();
// Do something
// Print something useful, TODO
System.out.println(v1.getSpeed());
}
}
As you can see in the first class, I have added a comment ("// throw exception") where I would like to throw an exception. Do I have to define my own class for exceptions or is there some general exception class in Java I can use?
You could create your own Exception class:
public class InvalidSpeedException extends Exception {
public InvalidSpeedException(String message){
super(message);
}
}
In your code:
throw new InvalidSpeedException("TOO HIGH");
You could use IllegalArgumentException:
public void speedDown(int decrement)
{
if(speed - decrement < 0){
throw new IllegalArgumentException("Final speed can not be less than zero");
}else{
speed -= decrement;
}
}
Well, there are lots of exceptions to throw, but here is how you throw an exception:
throw new IllegalArgumentException("INVALID");
Also, yes, you can create your own custom exceptions.
A note about exceptions. When you throw an exception (like above) and you catch the exception: the String that you supply in the exception can be accessed throw the getMessage() method.
try{
methodThatThrowsException();
}catch(IllegalArgumentException e)
{
e.getMessage();
}
It really depends on what you want to do with that exception after you catch it. If you need to differentiate your exception then you have to create your custom Exception. Otherwise you could just throw new Exception("message goes here");
The simplest way to do it would be something like:
throw new java.lang.Exception();
However, the following lines would be unreachable in your code. So, we have two ways:
Throw a generic exception at the bottom of the method.
Throw a custom exception in case you don't want to do 1.
Java has a large number of built-in exceptions for different scenarios.
In this case, you should throw an IllegalArgumentException, since the problem is that the caller passed a bad parameter.
You can define your own exception class extending java.lang.Exception (that's for a checked exception - these which must be caught), or extending java.lang.RuntimeException - these exceptions does not have to be caught.
The other solution is to review the Java API and finding an appropriate exception describing your situation: in this particular case I think that the best one would be IllegalArgumentException.
It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.

Categories

Resources