File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How do I throw an exception on purpose? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I throw an exception on purpose?" Watch "How do I throw an exception on purpose?" New topic

How do I throw an exception on purpose?

Reggie McDougal
Ranch Hand

Joined: Sep 27, 2004
Posts: 69
I want to check for a null value in my condtion I want to deliberatly throw an exception.

Can I use a method to throw an exception?

You can never drink too much
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
You throw an exception by using the throw keyword and creating an instance of some class that extends Exception:



Java API Documentation
The Java Tutorial
Sunil Manheri
Ranch Hand

Joined: Jul 07, 2004
Posts: 32
You can create your own Exception class and throw that excaption.

public class MyException extends Exception {

public MyException(){
super("Exception Occured!");


Then throw this Exception as:

throw new MyException();

TechMindViews - Technical Notes
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
To learn the basics of exception handling, I recommend reading
  • chapter 9 of Bruce Eckel's Thinking In Java Book
  • chapter 9 of David J. Eck's Introduction to Programming Using Java
  • chapters 80 & 81 of Bradley Kjell's Introduction to Computer Science using Java
  • Dick Baldwin's The Essence of OOP using Java, Exception Handling Article and
  • The Handling Errors with Exceptions Lesson of Sun's Java Tutorial
  • Then, when you're ready to have some fun, take a look at this past JavaRanch conversation as well as

    [How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
    Mahesh Bhatt
    Ranch Hand

    Joined: Sep 15, 2004
    Posts: 88
    Hi there,

    Just have to say one thing.Dirk,That list of links was great.


    Impossible is I M Possible
    I agree. Here's the link:
    subject: How do I throw an exception on purpose?
    It's not a secret anymore!