With those two pieces in place, we'll create a "driver" class with a main method to test our custom Java exception. A driver class to test (throw) the custom Java exception ")), and then (2) throw that exception with the throw keyword. ") Īs you can see, all you need to do to throw your custom exception is (1) create a new instance of the exception (new AlsCustomException("Anything but zero. Throw new AlsCustomException("Anything but zero. * Our test class to demonstrate our custom exception. To demonstrate how to throw our exception, here's a small example class with a method named getBar that will throw our custom exception ( AlsCustomException) if the method is given the value of zero as a parameter (sorry, not much imagination there, just trying to keep it simple): A method to throw a custom Java exception Public AlsCustomException(String message)Īs you'll see later there are more Exception class constructors you can override, but this is a good start for our example. As you can see, to create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor:Ĭlass AlsCustomException extends Exception To get started, this is pretty much the most simple possible Java custom exception class.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |