wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes java Exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java Exceptions" Watch "java Exceptions" New topic
Author

java Exceptions

pares gada
Greenhorn

Joined: Dec 22, 2004
Posts: 1
i have code such as:

MyException.java
package except;

public class MyException extends Exception
{
private String msg;

public MyException()
{
this.msg="Maths Wrong";
}
}


ExceptionThrow.java
package except;

public class ExceptionThrow

{
public static void main(String args[])
{
num(10);
num(0);
}
static void num(int x) throws MyException
{
if(x==0) throw new MyException();
}
}


I am not able to compile ExceptionThrow.java
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
what is the error ?
how do you compile it ?

and try to use the UBB CODE tags when showing code



pascal
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

The routine main() won't compile because it's calling num(), which declares that it throws MyException. That means main() either has to catch MyException, or it has to also declare that it throws this same exception.

These are your two choices whenever you call a method that throws a checked exception type. You either have to catch it, or you have to "pass it on" by declaring that your calling method throws it, too.


[Jess in Action][AskingGoodQuestions]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: java Exceptions
 
Similar Threads
problem with user defined exception
extending from Exception
Singleton class confusion
who can get the simplest code?
Counting down with loops