Program for User defined Exception in java
To create user defined exception first you should create a class by extending Exception class.
Create another class named as "UserExcep" to throw our own exception.
Write some logical conditions to throw your exception and the exception caught by catch block.
class BadString extends RuntimeException{ }
Create another class named as "UserExcep" to throw our own exception.
public class UserExcep
Write some logical conditions to throw your exception and the exception caught by catch block.
package javabynataraj.exceptions; import java.io.BufferedReader; import java.io.InputStreamReader; class BadString extends RuntimeException{ } public class UserExcep{ public static void main(String[] args) { try{ System.out.println("Enter the String: "); BufferedReader sb=new BufferedReader(new InputStreamReader(System.in)); String s=sb.readLine(); if(s.equals("hateyou")){ throw new BadString(); } System.out.println("I Accept your String"); }catch(Exception e){ System.out.println("Please enter a good String"); //e.printStackTrace(); } } }