182

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

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Mazzy
  • 13,354
  • 43
  • 126
  • 207
  • 2
    Can some of the answers *please* discuss checked vs. unchecked exceptions? What does extending Exception imply? RuntimeException? Throwable? –  Dec 07 '11 at 22:50
  • http://stackoverflow.com/questions/1070590/how-can-i-write-an-exception-by-myself , http://stackoverflow.com/questions/3505111/how-can-i-customize-custom-exceptions-in-java , http://stackoverflow.com/questions/1176130/java-exception-handling-custom-exception –  Dec 07 '11 at 22:52
  • There is 1) creating a custom exception type/class (as shown so many times) and 2) raising the exception. To raise an exception, simply pass the appropriate instance to `throw`, normally: `throw new MyFormatExpcetion("spaces are not allowed");` -- you could even use the *standard* [ParseException](http://docs.oracle.com/javase/6/docs/api/java/text/ParseException.html), without "creating" a custom exception type. –  Dec 07 '11 at 22:55
  • @pst Good point. I've added some information on checked vs unchecked exceptions in my answer. – Laf Dec 07 '11 at 23:31
  • See video tutorials about exception class creation and handling in Java. http://www.bitspedia.com/2013/11/exception-handling-in-java-video.html – Asif Shahzad Nov 18 '13 at 18:36

9 Answers9

263

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
}
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • This was just the declaration for the exception, it can be thrown with a simple throw new WordContainsException(); Updated and added usage. – Rion Williams Dec 07 '11 at 22:52
  • What should contain `catch()`? – Mazzy Dec 07 '11 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 – Rion Williams Dec 07 '11 at 23:13
  • 8
    You should add two more constructors (`WordContainsException(Throwable)` and `WordContainsException(String, Throwable)`) to properly support [exceptions chaining](http://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html) – Danilo Piazzalunga Sep 18 '13 at 13:11
  • @DaniloPiazzalunga you don't need to support exception chaining unless you're using exception chaining. – wild_nothing Feb 13 '14 at 03:53
  • Exception chaining is important to preserve debugging information: http://www.javaworld.com/article/2075601/testing-debugging/exceptional-practices--part-2.html – Danilo Piazzalunga Feb 13 '14 at 14:02
126

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.

Daniel Kutik
  • 6,997
  • 2
  • 27
  • 34
Laf
  • 7,965
  • 4
  • 37
  • 52
  • 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 07 '11 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 07 '11 at 23:30
16

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!");
}
Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
  • 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 '15 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 '15 at 18:44
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.

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
emory
  • 10,725
  • 2
  • 30
  • 58
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);
jpaugh
  • 6,634
  • 4
  • 38
  • 90
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • 1
    These are all RuntimeExceptions, right? Perhaps a careful programmer would avoid overusing them. – jpaugh Oct 15 '15 at 18:55
  • 1
    @jpaugh thanks for letting me swallow my own word ;). Appreciate it. – Joop Eggen Oct 16 '15 at 07: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 '15 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 '15 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 '15 at 00:27
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

Robin
  • 36,233
  • 5
  • 47
  • 99
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/

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
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.

Thomas
  • 5,074
  • 1
  • 16
  • 12
2

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

GETah
  • 20,922
  • 7
  • 61
  • 103