180

I would like to create a custom exception in Java, how do I do it?

...

try{

...

String word=reader.readLine();

if(word.contains(" "))
  /*create custom exception*/

}
catch(){

When I create my custom exception with throw new..., I obtain the error unreported exception...must be caught or declared to be thrown

5

9 Answers 9

261

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
{
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)
      {
         super(message);
      }
 }

Usage:

try
{
     if(word.contains(" "))
     {
          throw new WordContainsException();
     }
}
catch(WordContainsException ex)
{
      // Process message however you would like
}
6
  • This was just the declaration for the exception, it can be thrown with a simple throw new WordContainsException(); Updated and added usage. Dec 7, 2011 at 22:52
  • What should contain catch()?
    – Mazzy
    Dec 7, 2011 at 23:07
  • You seem to already have the catch within your code, I'm not sure exactly where you want the exception to be thrown. You could put it before the catch section, or inside of it. I edited it assuming how you might want to use the exception Dec 7, 2011 at 23:13
  • 8
    You should add two more constructors (WordContainsException(Throwable) and WordContainsException(String, Throwable)) to properly support exceptions chaining Sep 18, 2013 at 13:11
  • @DaniloPiazzalunga you don't need to support exception chaining unless you're using exception chaining. Feb 13, 2014 at 3:53
125

You need to create a class that extends from Exception. It should look like this:

public class MyOwnException extends Exception {
    public MyOwnException () {

    }

    public MyOwnException (String message) {
        super (message);
    }

    public MyOwnException (Throwable cause) {
        super (cause);
    }

    public MyOwnException (String message, Throwable cause) {
        super (message, cause);
    }
}

Your question does not specify if this new exception should be checked or unchecked.

As you can see here, the two types are different:

  • Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.

  • Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException

Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.

2
  • Why does it have to look like that? (1) If I am creating my own proprietary exception, I will make it package-private (or private if it is not top-level). (2) Same thing wrt to the constructors. (3) I won't define 4 constructors unless I need them.
    – emory
    Dec 7, 2011 at 23:17
  • 1
    (1) You should make your new exception a public one, so that methods calling your method may catch this new exception and do something with it (if you mean this new exception to be a checked exception, see my edit. (2) Make the constructors public, no need to hide them. (3) You can get rid of the constructors you don't need, all 4 are not mandatory.
    – Laf
    Dec 7, 2011 at 23:30
17

Great answers about creating custom exception classes. If you intend to reuse the exception in question then I would follow their answers/advice. However, If you only need a quick exception thrown with a message then you can use the base exception class on the spot

String word=reader.readLine();

if(word.contains(" "))
  /*create custom exeception*/
  throw new Exception("My one time exception with some message!");
}
2
  • 8
    This is really bad practice, because there is no way for the calling code to to distinguish, "I want to catch every kind of exception and do something generic" from, "I want to catch specifically that so-called one-time exception and do something in particular". The former kind of catch should only be used in very limited conditions --- such as in a top-level loop --- which exacerbates the situation even more.
    – jpaugh
    Oct 15, 2015 at 18:42
  • It would be better (and still debatable) to have a utility exception class called OneTimeException or something. Then, the caller would have a chance to distinguish them somewhat, rather than catching every exception in all circumstances.
    – jpaugh
    Oct 15, 2015 at 18:44
12

As a careful programmer will often throw an exception for a special occurrence, it worth mentioning some general purpose exceptions like IllegalArgumentException and IllegalStateException and UnsupportedOperationException. IllegalArgumentException is my favorite:

throw new IllegalArgumentException("Word contains blank: " + word);
5
  • 1
    These are all RuntimeExceptions, right? Perhaps a careful programmer would avoid overusing them.
    – jpaugh
    Oct 15, 2015 at 18:55
  • 1
    @jpaugh thanks for letting me swallow my own word ;). Appreciate it.
    – Joop Eggen
    Oct 16, 2015 at 7:59
  • Sorry! I didn't mean to be rude. Runtime exceptions do have their place, especially for what you are recommendeing. However, I was surprised when I glanced at the docs, and saw the RuntimeException superclass.
    – jpaugh
    Oct 16, 2015 at 14:47
  • @jpaugh not considered rude, in fact I liked the irony. My answer intended to mention the reusable exceptions. That those were RuntimeExceptions so do not require a handling is worth your mention.
    – Joop Eggen
    Oct 16, 2015 at 14:58
  • Awesome! I love your integrity. Actually, I'm just getting back into Java, so I'm tripping on beginner things (e.g. related to exceptions), while I haven't forgotten some advanced things (mostly related to good style, API design). At any rate, your post has been imminently helpful.
    – jpaugh
    Oct 19, 2015 at 0:27
12

Since you can just create and throw exceptions it could be as easy as

if ( word.contains(" ") )
{
     throw new RuntimeException ( "Word contains one or more spaces" ) ;
}

If you would like to be more formal, you can create an Exception class

class SpaceyWordException extends RuntimeException
{

}

Either way, if you use RuntimeException, your new Exception will be unchecked.

1
  • So no new custom made 'Exception' can be checked exception?
    – AHF
    Jul 4, 2020 at 2:30
5

An exception is a class like any other class, except that it extends from Exception. So if you create your own class

public class MyCustomException extends Exception

you can throw such an instance with

   throw new MyCustomException( ... );
   //using whatever constructor params you decide to use

And this might be an interesting read

3

You just need to create a class which extends Exception (for a checked exception) or any subclass of Exception, or RuntimeException (for a runtime exception) or any subclass of RuntimeException.

Then, in your code, just use

if (word.contains(" "))
    throw new MyException("some message");
}

Read the Java tutorial. This is basic stuff that every Java developer should know: http://docs.oracle.com/javase/tutorial/essential/exceptions/

2

You have to define your exception elsewhere as a new class

public class YourCustomException extends Exception{

//Required inherited methods here
}

Then you can throw and catch YourCustomException as much as you'd like.

2

You can create you own exception by inheriting from java.lang.Exception Here is an example that can help you do that.

Not the answer you're looking for? Browse other questions tagged or ask your own question.