Generating Custom Exception in java

Custom Exception
  • Java provide throw keyword to generate your own Exception.
    you can generate your own Exception class by Extending another Predefined
    Exception class.
    syntax:
    Throw new MyException();
How to generate custom Exception in java ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
package exceptionHandling;
 
import java.util.Scanner;
 
//class that extends Throwable
 
class Myexception extends Throwable
 {
 
 }
 
//main class
public class Throw 
{
public static void main(String[] args) 
{
 
	Scanner c=new Scanner(System.in);
	System.out.println("enter your age");
 
	int n=c.nextInt();
 
	System.out.println("checking......");
 
	if(n<18)
	{
		try 
		{	
	          throw new myexception();
		}
 
		catch (myexception e) 
		{
		  System.out.println("try next year,your age is not valid");
		}
 
	}
 
	else
	{
	 System.out.println("thank you for voting ");
	}	
 
  }
 
}
output:
 
enter your age
17
checking......
try next year,your age is not valid

Throws keyword in java

Throws
  • Throws is used to propagate the Exception.
  • You can write throws keyword at the time of method declaration.
  • You have handle that Exception at the time of calling that method.
  • Throws is class type it means after throws you have to write Exception class.
How to Propagate Exception in java using Throws ?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 
package exceptionHandling;
 
 
class Demo123
{
 
	void printnumber(int n,int m) throws InterruptedException 
	{
 
		for(;n<=m;n++)
		{
			System.out.println(n);
			Thread.sleep(1000);	
 
		}
	}
}
 
 
public class UseOfThrows
{
public static void main(String[] args) 
{
 
	System.out.println("****************************");
 
     Demo123 obj1=new Demo123();	
 
 
       try 
          {
	    obj1.printnumber(1, 5);
	  } 
 
     catch (InterruptedException e) 
	   {
		e.printStackTrace();
	   }
 
 
 
	System.out.println("*****************************");
  }
 
}
 
output:
 
****************************
1
2
3
4
5
*****************************