0

I have 2 classes, one that implements a double lookup( int i); and one where I use that lookup(int i) in solving a question, or in this case printing the lookup values. This case is for an array.

So I read the exception documentation or google/textbook and come with the following code:

public double lookup(int i) throws Exception
{
    if( i > numItems)
        throw new Exception("out of bounds");
    return items[i];        
}

and take it over to my class and try to print my set, where set is a name of the object type I define in the class above.

public void print()
{
    for (int i = 0; i < set.size() - 1; i++)
    {
        System.out.print(set.lookup(i) + ",");

    }
    System.out.print(set.lookup(set.size()));
}

I'm using two print()'s to avoid the last "," in the print, but am getting an

unhandled exception Exception (my exception's name was Exception)

I think I have to catch my exception in my print() but cannot find the correct formatting online. Do I have to write

catch exception Exception? because that gives me a syntax error saying invalid type on catch.

Sources like http://docs.oracle.com/javase/tutorial/essential/exceptions/ are of little help to me, I'm can't seem to grasp what the text is telling me. I'm also having trouble finding sources with multiple examples where I can actually understand the coding in the examples.

so could anybody give me a source/example for the above catch phrase and perhaps a decent source of examples for new Java programmers? my book is horrendous and I cannot seem to find an understandable example for the above catch phrase online.

user1702633
  • 111
  • 3
  • 5
  • 8

4 Answers4

1

I wouldn't throw Exception ever.

In your case, IndexOutOfBoundException or InvalidArgumentException would eb a better choice. As these are not checked Exceptions, you don't need to catch them.

public double lookup(int i) {
    if(i >= numItems) // assuming numItems is not items.length
        throw new IndexOutOfBoundException("out of bounds " + i + " >= " + numItems);
    return items[i];        
}

Note: the check should be >=

Your print() method will now compile unchanged.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    He is yet to understand Exception:) I would say it would be overdose. – Amit Deshpande Sep 27 '12 at 09:35
  • oh...yeah that sounds better for this. I was just trying to avoid predefined tools given by Java, as I'm still in the beginner level and want to try things for myself. – user1702633 Sep 27 '12 at 09:38
  • Why not start with a beginner book then rather than throwing yourself at exceptions? In fact, one of the stronger points of java is the fact that you *don't* have to do alot of things by youtself. – Shark Sep 27 '12 at 09:40
  • @Peter Should we throw explicit exceptions for this particular case.? ArrayIndexOutOfBoundsException should suffice I guess. – Ajay George Sep 27 '12 at 09:44
  • You can add it to the `throws` clause if you wish, but its optional in this case. I prefer to do this to make it clear an exception could be throw, but mostly because I don't always write javadocs. ;) – Peter Lawrey Sep 27 '12 at 09:45
1

What is Exception?

Exceptions are for exceptional conditions. Conditions that normally do not occur. Take an example you went to withdraw money and your account has 100 balance and you asked for 200 then ATM should tell you that you have insufficient balance.

Types of Exceptions

  • Checked Exception

    These are conditions where application wants to recover from it. Like example given above application will give you error and will continue working.

  • Error

    This is an exceptional condition which is external to application. We say OutOfMemoryError when there isn't enough memory available and application can not recover from it.

  • Runtime Exception /Unchecked Exception

    These exceptions are applications exception but in this case application can not recover from it. E.g NullpointerException if value is null and you try do something nasty with it.

so of above three only checked exceptions need to be cached.

How to throw and Catch Checked Exception

Exception or any subclass of Exception is a checked exception. A checked exception can be thrown using throw clause. Once you throw an exception it becomes mandatory for you to include that in method declaration using throws clause.

So whoever want to use this method will now have to handle that exception. Handling exception means invoking alternative flows. Like in our case we displayed text to user "Error Invalid account number."

Calling function can also choose to propagate exceptions by adding throws clause for those exceptions which are thrown by method it is calling.

Generate:
public static double withdraw(int i) throws Exception {
    if (i <= 0)// Out of bounds
        throw new Exception("Invalid Account Number");
    return 0.0;// something;
}

Handle:

try {
        withdraw(0);
    } catch (Exception e) {
        // do something with exception here.
        // Log the exception
        System.out.println("Error Invalid account number.");
    }

Propagate:
      public static double callWithdraw(int i) throws Exception {//Propagate exceptions
        return withdraw(i);
      }
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
  • but this is what I don't understand- why do i have to try withdraw(0) if I already know that i <= 0 is out of bounds and have already defined it as such? I can't see why I have to try it, and why I would have to catch it. Shouldn't it be that the program auto-catches when my if is in effect? – user1702633 Sep 27 '12 at 09:57
  • @user1702633 added some more information. Hope it clears doubts. Whichever class wants to use that exception can use it. You can also propagate exception meaning rather than handling just include it in throws clause. – Amit Deshpande Sep 27 '12 at 10:03
0

Try this

try
{
    print(); //print() needs to throw the same exception
} catch(Exception e)
{
   //handle exception
   System.err.println(e.getMessage()+"\n\n"+e.printStackTrace());
}
//finally {
// cleanup here if you like
// }

or this

public void print()
{
    for (int i = 0; i < set.size() - 1; i++)
    {
        try
        {
            System.out.print(set.lookup(i) + ",");
        } catch(Exception e)
        {
          //handle it here
        }
    }
    System.out.print(set.lookup(set.size()));
}

Do note that using "throws" is kind of a easy way out; it's a cheap delegation that sometimes makes coding easier... if you can, you should try to always use try/catch instead of throws.

Just be aware that whenever you use something with "throws" eventually you will have to put that in a try/catch block and deal with it properly.

Shark
  • 6,513
  • 3
  • 28
  • 50
  • so I take it that I should stop using throws and I am better off using try/catch all the time. Thanks. – user1702633 Sep 27 '12 at 09:37
  • If you can deal with the exception being raised, then absolutely. IMHO, "try/catch" vs "throws" is kinda like "iteration" vs "recursion'. You will learn when to use each one :) – Shark Sep 27 '12 at 09:39
  • 1
    return type of e.printStackTrace() is void. – 2787184 Mar 15 '18 at 17:08
  • @ravi you're right, i forgot to pass a PrintWriter to it, and collect it's logs which will have a `String` return type. – Shark Mar 15 '18 at 18:23
0

Generally to denote improper arguments passed into your method, use IllegalArgumentException which is a RuntimeException and should not be caught.

In this specific case you don't have to write any extra code, the ArrayIndexOutOfBoundsException should take care of improper array access.

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Ajay George
  • 11,759
  • 1
  • 40
  • 48