1

I have some basic questions re: the basics of exception handling in Java. I have implemented my own exception class, myArrayException, which extends NegativeArraySizeException. The code is pretty basic and the entire thing shown below:

class myArrayException extends NegativeArraySizeException {

    myArrayException() {
        super("my custom exception class");
    }
}

public class myClass {
    public static void main(String args[]) {
        try {
            myMethod();
        } catch (myArrayException e) {

            System.out.print("hello");
        }
    }

    public static void myMethod() {
        int size = 5;
        if (size < 0) {
            throw new myArrayException();
        }
        int[] a = new int[size];
        System.out.print("code successfully reached");
    }
}

The code works fine. When I set negative values to the "size" variable the code in the block:

catch(myArrayException e) {
    System.out.print("hello");
}

gets executed properly. But if i add

public static void myMethod() throws myArrayException

and remove the if condition, then the catch block that I have written does not execute. Can anyone tell me why? Especially since I specify "throws myArrayException" for that method?

Perception
  • 79,279
  • 19
  • 185
  • 195
user2056245
  • 595
  • 1
  • 9
  • 24
  • Please post code that demonstrates the problem you are having. As-is your question makes little sense. If you throw that exception, the catch block will be executed. – Brian Roach Mar 06 '13 at 15:15
  • 2
    OT: It is highly recommended to name your classes with a capital letter at the beginning. – Jiri Kremser Mar 06 '13 at 15:17
  • The statement " int size = -13; will NEVER cause an excepption to be thrown no matter how hard you try. – Java42 Mar 06 '13 at 15:18
  • @ChuckFricano What do you mean? If you run the code with `size=-13`, it does cause the exception – Ankit Mar 06 '13 at 15:21
  • @Ankit The exception detected/thrown on the line "if (size < 0) throw new myArrayException();" , not in the line "int size = -13". He expects an exception to be thrown even without the "if (size < 0)" statement. – Java42 Mar 06 '13 at 15:26
  • yes, what i want to know is "myMethod throws myArrayException " have any effect on my code? I dont think so.if i remove the whole "if" block then JRE itself handles it . so the "throw" statement in myMethod is important and not "myMethod throws myArrayException " , because, even without this statement code works fine.... do why add this statement? – user2056245 Mar 06 '13 at 15:30

3 Answers3

4

throws means that the function can throw the exception. It doesn't mean that it always throws the exception.

In short, adding throws statement make sure that whoever calls the method must add try.. catch block for this exception.

Read checked and unchecked exceptions

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • what i want to know is "myMethod throws myArrayException " have any effect on my code? I dont think so.if i remove the whole "if" block then JRE itself handles it . so the "throw" statement in myMethod is important and not "myMethod throws myArrayException " , because, even without this statement code works fine.... do why add this statement? am i right? – user2056245 Mar 06 '13 at 15:35
0

There is a tutorial on the oracle site you should study. It will help you understand exceptions. The link is:

http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html

Java42
  • 7,628
  • 1
  • 32
  • 50
0

Adding to the info on the throws keyword for Java, it appears you may have written a program that does in fact not execute. Or rather, it is halted by an unhandled exception. You say

But if i add public static void myMethod() throws myArrayException and remove the if condition

If by "the if condition", you mean this check:

    if (size < 0) {
        throw new myArrayException();
    }

Then MyMethod no longer throws myArrayException. Instead, the statement int[] a = new int[size]; will throw a NegativeArraySizeException, which you are not catching, making it an unhandled exception, which usually halts execution of the program. In that case, the line System.out.print("code successfully reached"); also won't execute, making it appear your program is doing nothing.

To answer your specific question (full disclosure, it's been forever since I used Java), the throws keyword is more a disclaimer on your method. It doesn't affect the compilation or execution of the method. As baraky excellently states:

throws means that the function can throw the exception. It doesn't mean that it always throws the exception.

  1. "myMethod throws myArrayException " have any effect on my code? Nope, no effect. It's just a warning to others.
  2. If i remove the whole "if" block then JRE itself handles it? JRE handles any uncaught exception because it is the highest level program. If you remove the if block and the throw statement inside of it, then a NegativeArraySizeException is thrown when a netagive size is passed in (from the line of the array allocation: int[] a = new int[size];), instead of a MyArrayExcpetion.
  3. So the throw statement in myMethod is important and not myMethod throws myArrayException? Important is a relative term. The throw statement is important to the immediately executing code as it has an impact on the program flow and execution. The throws myArrayException on the method declaration does not have any immediate impact. BUT if you expect this code to be widely used, by others or even by yourself over a period of time long enough where you might not remember what you were thinking when you wrote every last line of the application, then it becomes very important, because...
  4. because, even without this statement code works fine.... why add this statement? throws basically tells whoever else looks at your code "Hey, you better handle these exceptions if you call this code or else your program might crash." You don't have to include this declaration, but it makes everyone's lives easier if you do.

If your method catches an exception, then it should not say it throws that exception. Breaking it down in code using the "checked vs. unchecked" terminology that seems to have become prevalent since I used Java:

public static void MyMethod() throws MyArrayException{
    int size = 5;
    if (size < 0) {
        // Unchecked exception, properly warned callers of MyMethod that you will
        // throw it and they need to catch it
        throw new MyArrayException();
    }
    if (size == 3) {
        // Unchecked exception, but you didn't warn callers of MyMethod
        // No functional impact for your code, but if someone else is relying
        // on this method, they won't know catch this and will likely be
        // irate with you if it crashed their program
        throw new IHateThreesException();
    }

    try {
        int[] a = new int[size];
    }
    catch(NegativeArraySizeException)
    {
        // This is a checked exception, because you checked for it with a
        // try-catch block and don't re-throw it
        System.out.print("Code checked for this but size " + size + " was negative anyways!");
    }
    catch(OutOfMemoryExcpetion ome)
    {
        // I _think_ this is still an unchecked exception, because the I choose
        // to re-throw it. Regardless, we explicitly throw this exception so
        // there is no excuse for us to not have included it in the throws
        // declaration
        System.out.print("I just canno' do it captain, I don't have the memory!"
            + "(Free up some memory and try again)");
        throw ome;
    }
    System.out.print("code successfully reached");
}

The examples are cobbled together from what others have said, and my own feeble memory of Java. I don't know the exact definition of a checked exception, but hopefully I capture at least the essence of what it is and how it differs from an unchecked exception. Please correct me if I got this wrong.

Edit: Doing some more reading, I think I am very wrong about what is and is not a checked exception. Hopefully someone can correct me.

Patrick M
  • 10,547
  • 9
  • 68
  • 101
  • what i want to know is "myMethod throws myArrayException " have any effect on my code? I dont think so.if i remove the whole "if" block then JRE itself handles it . so the "throw" statement in myMethod is important and not "myMethod throws myArrayException " , because, even without this statement code works fine.... do why add this statement? am i right? – user2056245 Mar 06 '13 at 16:15