In java predefined Exceptions throws automatically. like,
int a=10, b=0;
c = a/b;
throws ArithmeticException
int a[3] = {1, 2, 3};
int b = a[4];
throws ArrayOutOfBoundException
wherein in case of user-defined exceptions we should create an object of that Exception class and throw it manually.Can I make my own Exception to behave like the above two cases?
Can I make my own Exception to behave like the above two cases?
No, it would have to be built into the JVM.
You may, but you have to catch the original and then throw your own.
try {
int a=10, b=0;
int c=a/b;
catch (Exception e){
//disregard exception, throw your own
throw new MyCustomException("My Custom Message");
}
Or, if you have a condition where you want to throw an exception on a case where an exception wouldn't normally exist, you just throw it!
// In this case, only move forward if a < b
int a = 10, b = 0;
if (a >= b)
throw new MustBeLessThanException("a must be less than b!");
Or something silly like that.
Be sure to make the custom class extend Exception or one of the subclasses.
No, all you can do is catch and then throw your own:
try {
int a=10, b=0;
c = a/b;
} catch (ArithmetikException e) {
throw MyException("Bad!", e); // pass in e to getr a meaningful stacktrace
}
But I really wouldn't recommend that (except in cases where you have to, ie. when implementing an interface that doesn't declare an exception that might be thrown in your code). But then again, your example both are RuntimeExceptions (which are unchecked) and those don't have to be declared.
Related
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;
}
}
So I'm trying to catch exceptions where I can't return a Directory, but Java won't let me. How do I structure the code so that Java will let me run it?
public Directory pathToDir(String path) throws Exception {
String[] arrayPath = path.split("/");
Directory cwd_copy = FileSystem.getRoot();
try {
// full path
if (path.startsWith("/")) {
for (int x = 1; x < arrayPath.length; x++) {
if (stuff) {
} else {
throw new Exception();
}
}
}
return cwd_copy;
}
catch (Exception e) {
pathErrorMsg();
}
}
No, you may be throwing an exception, but then you catch it and do nothing with it! If you step through that code logically, you'll see that there are possible pathways for the method to end without a Directory being returned and for no exceptions to be thrown. That won't fly.
Consider instead,....
public Directory pathToDir(String path) throws PathToDirException {
String[] arrayPath = path.split("/");
Directory cwd_copy = FileSystem.getRoot();
// full path
if (path.startsWith("/")) {
for (int x = 1; x < arrayPath.length; x++) {
if (stuff) {
} else {
throw new PathToDirException( /* some text goes in here! */ );
}
}
}
return cwd_copy;
}
Where PathToDirException is a checked exception class you've created for problems with this method/class.
Or if you have a try/catch block in the method, and need to then throw an exception, throw your new Exception class, but pass the caught exception into your new exception as a constructor parameter.
If I understand your question, you need a return at the end of your method (in case you catch an Exception instead of returning cwd_copy)
return cwd_copy; // <-- this didn't happen.
} catch (Exception e) {
pathErrorMsg();
// return null; // <-- you could return here.
}
return null; // <-- so you need something. null or cwd_copy
Or add a return in the catch block.
Because an exception could be caught1, a value must still be returned from the catch path.
try {
maybeThrowException();
return X;
}
catch (Exception e) {
// But what is returned here?
}
Either don't catch the exception, [re]throw an exception, or return a value in the case when the catch block is entered.
Since the method is declared to throw an Exception, it probably should throw one on failure - the method contract should specify the result in such a case.
1 Java actually isn't that smart, even if it is a logical way to think about it. The try/catch is treated like an if/else here and all branches must logically lead to a return (or throw). It would still be a compiler error even if the try was empty and could never throw an exception. Consider the following comparison:
if (true) {
return X;
} else {
// But what is returned here?
// (Java does not consider that this can never be reached,
// just as it does not logically consider the content of a `try`.)
}
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.
I wrote a code which checks all kinds of conditions.
If it meets the condition it does what it is supposed to, otherwise I want it to throw an
exception.
Is there any special syntax for that? Otherwise the compiler wants me to return any array,
which I don't want to, due to the pre-condition.
Here is part of my code:
public static int [] code(int[]arr){
if ((arr!=null)&&(chack4and5(arr))&&(arr[arr.length-1]!=4)&&(TwoFours(arr))){
int k=0;
for(int i = 0; i<=arr.length-1; i++){
if (arr[i] == 4){
int place= pos(arr,k);
arr[place]=arr[i+1];
arr[i+1]=5;
k=k+3;
}
}
return arr;
}
else {
System.out.println("Please enter a legal array which matches the pre- conditions");
}
}
}
The way to throw an exception is
throw new IllegalArgumentException(
"Please enter a legal array which matches the pre- conditions");
IllegalArgumentException is a Java runtime exception suitable for the current situation, but of course you can choose another one, or create and use your own type too. The only restriction is that it must be a subclass of java.lang.Exception.
I would rearrrange your code though to check the preconditions first, then proceed if everything's fine - I find this more readable:
if (arr == null || !chack4and5(arr) || arr[arr.length-1] == 4 || !TwoFours(arr)) {
throw new IllegalArgumentException(
"Please enter a legal array which matches the pre- conditions");
}
int k=0;
for(int i = 0; i<=arr.length-1; i++){
if (arr[i] == 4){
int place= pos(arr,k);
arr[place]=arr[i+1];
arr[i+1]=5;
k=k+3;
}
}
return arr;
(In fact, I would even prefer extracting the precondition check into a separate method - but I leave this to you.)
throw new IllegalArgumentException(
"Please enter a legal array which matches the pre- conditions")
java.langIllegalArgumentException is a RuntimeException that means some of the arguments are not as they are expected to be. Since it is an unchecked exceptions, your callers are not forced to handle it in any way (as opposed to checked exceptions)
You can throw an Exception by yourself. Maybe the best way to do this is defining a custom exception and then throwing it. If you don't want to do that use an IllegalArgumentException.
Here an example of a custom exception:
public static int [] code(int[]arr) {
if ((arr!=null)&&(chack4and5(arr))&&(arr[arr.length-1]!=4)&&(TwoFours(arr))){
int k=0;
for(int i = 0; i<=arr.length-1; i++){
if (arr[i] == 4){
int place= pos(arr,k);
arr[place]=arr[i+1];
arr[i+1]=5;
k=k+3;
}
}
return arr;
}
else {
throw new MyException("No legal array");
}
}
}
And here your custom exception:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
If the exception is that something about your arguments is illegal, then throw an IllegalArgumentException:
throw new IllegalArgumentException("descriptive message")
You may want to take a look at Oracle's tutorials on exceptions.
To throw an exception, you use the throw keyword.
To mark that a method may throw an exception, use the throws keyword, like
public static void foo() throws SomeException
You can throw exception with this line
throw new SomeKindOfException("Exception description"); // or any other exception, also yours...
But you need to specify at the method declaration:
public static int [] code(int[]arr) throws SomeKindOfException{
See Oracle tutorial for more
Why won't Java let me assign a value to a final variable in a catch block after setting the value in the try block, even if it is not possible for the final value to be written in case of an exception.
Here is an example that demonstrates the problem:
public class FooBar {
private final int foo;
private FooBar() {
try {
int x = bla();
foo = x; // In case of an exception this line is never reached
} catch (Exception ex) {
foo = 0; // But the compiler complains
// that foo might have been initialized
}
}
private int bla() { // You can use any of the lines below, neither works
// throw new RuntimeException();
return 0;
}
}
The problem is not hard to work around, but I would like to understand why the compiler does not accept this.
Thanks in advance for any inputs!
try {
int x = bla();
foo = x; // In case of an exception this line is never reached
} catch (Exception ex) {
foo = 0; // But the compiler complains
// that foo might have been initialized
}
The reason is because the compiler cannot infer that the exception can only be thrown before foo is initalized. This example is a special case where it is obvious that that is true, but consider:
try {
int x = bla();
foo = x; // In case of an exception this line is never reached...or is it?
callAnotherFunctionThatThrowsAnException(); // Now what?
} catch (Exception ex) {
foo = 0; // But the compiler complains
// that foo might have been initialized,
// and now it is correct.
}
To write a compiler to handle very specific cases like this would be an immense task - there are likely very many of them.
To be a pedant, Thread.stop(Throwable) could throw an exception immediately after the try block assignment.
However, the rules with definite assignment and allied terms are complex enough. Check the JLS. Trying to add more rules would complicate the language and not provide significant benefit.
How about a thrown Error?