Java Beginners - Java For Beginners Java Exception Rating: 5.0/5 (1 vote cast) | Level : Beginners Author : Arunkumar S Download Source : exception.zip
Java Exception - User Defined ExceptionProgrammers could also create user-defined exceptions, specific to their business. Let's say you are in business selling bikes and need to validate a customers order. Create a new class TooManyBikesException that is derived from the class Exception or Throwable, and if someone tries to order more bikes than you can ship - just throw this exception: /** * * @author Arunkumar Subramaniam * */ public class ArunException extends Exception{ public ArunException(Exception e){ super(e); } } /** * * @author Arunkumar Subramaniam * */ public class TestException { void hello()throws ArunException{ try{ int i=0; i=10/i; }catch(ArithmeticException e){ throw new ArunException(e); } } void altHello()throws Exception{ int i=10; i=10/i; if(i==1){ throw new ArunException(new Exception("by mi2arun")); } } public static void main(String str[]){ TestException t=new TestException(); try { t.hello(); } catch (ArunException e) { e.printStackTrace(); } try { t.altHello(); } catch (ArunException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } output : ArunException: java.lang.ArithmeticException: / by zero at TestException.hello(TestException.java:9) at TestException.main(TestException.java:26) Caused by: java.lang.ArithmeticException: / by zero at TestException.hello(TestException.java:7) ... 1 more ArunException: java.lang.Exception: by mi2arun at TestException.altHello(TestException.java:18) at TestException.main(TestException.java:31) Caused by: java.lang.Exception: by mi2arun ... 2 more < Previous 1 | 2 |
Discussion about this tutorial
 Start a new Discussion | Read All Discussion
|