• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java Exceptions

 
pares gada
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic