• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

java Exceptions

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Curse your sudden but inevitable betrayal! And this tiny ad too!
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic