0% found this document useful (0 votes)
11 views21 pages

Exception Handling

The document explains exception handling in Java, detailing its purpose, types (checked and unchecked exceptions), and methods to handle them (try-catch and throws). It emphasizes the importance of handling exceptions to ensure normal program termination and provides examples of various exception scenarios. Additionally, it covers advanced topics like multiple catch blocks, try-with-resources, and printing exception information.

Uploaded by

kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views21 pages

Exception Handling

The document explains exception handling in Java, detailing its purpose, types (checked and unchecked exceptions), and methods to handle them (try-catch and throws). It emphasizes the importance of handling exceptions to ensure normal program termination and provides examples of various exception scenarios. Additionally, it covers advanced topics like multiple catch blocks, try-with-resources, and printing exception information.

Uploaded by

kiran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 21

Exception handling

The dictionary meaning of the exception is abnormal termination.


Exception is a object occured during runtime to disturb the normal flow of the
execution.
st-1
st-2
st-3 exception raised
st-4

Compile time we will get only syntaxErrors.

In application whenever the exception occurred,


1. Program terminated abnormally.
2. Rest of the application is not executed.

There are two ways to handle the exception,


a. try-catch
b. throws

once we handle the exception


1. Program terminated normally.
2. Rest of the application is executed.

Note :The main objective of exception handling is to get the normal termination of
the applicaion.

Types of Exceptions: As per the sun micro systems standards The Exceptions are
divided into three types
1. Checked Exception
2. Unchecked Exception
3. Error

Unchecked Exception:
a. The Unchecked Exception are caused due to end user inputproblems.
b. The exceptions are not checked by compiler are called Unchecked Exception
ex : AE, AIOBE , NPE , NFE...etc
c. These are child class of RuntimeException.

class Test {
public static void main(String[] args) {
System.out.println("ratan");
System.out.println(10/0);
ArithmeticException

int[] a = {10,20,30};
System.out.println(a[6]);
java.lang.ArrayIndexOutOfBoundsException

System.out.println("ratan".charAt(12));
StringIndexOutOfBoundsException

int[] arr = new int[-6];


java.lang.NegativeArraySizeException
System.out.println("rest of the application");
}
}

Checked Exception:
a. The checked exceptions are caused due to developer issues.
b. The Exceptions which are checked by the compiler are called Checked
Exceptions.
FileNotFoundException,SQLException,InterruptedException ……..etc
c. these are child class of Exception.

import java.io.*;
class Test
{ public static void main(String[] args)
{ try{
FileInputStream fis = new FileInputStream("abc.txt");
}
catch(FileNotFoundException f)
{ System.out.println("file is not present..."+f);
}
System.out.println("rest of the application");
}
}

Note:
1. un-checked exceptions are caused due to end user input problems.
checked exceptions are caused due to developer mistake.

2. The checked exceptions are safe becaue the compiler will give some information
about the exception at compile time itself.
If the application contains checked exception must handle the exception,
otherwise compiler generates error message.

unchecked exception compiler is not giving the information.

3. Whether it is a checked Exception or unchecked exception, the exceptions are


raised at runtime but not compile time.

4. whether it is a checked or unchecked exception, must handle the exception either


by using try-catch or by using throws keyword.

5. All un-checked exceptions are child class of RuntimeException.


All checked exceptions are child class of Exception.

//errors:
1.The exceptions are occurred due to the fallowing reasons
a. Developer mistakes
b. End-user input mistakes.
But errors are caused due to lack of system resources.
StackOverFlowError, OutOfMemoryError …………etc

2. It is possible to handle the exceptions by using try-catch blocks or throws


keyword but it is not possible to handle the errors.

3. Error is an un-checked type exception.


class Test
{ public static void main(String[] args)
{ int[] a = new int[1000000000];
}
}
java.lang.OutOfMemoryError: Java heap space

Note:
The Throwable class is the superclass of all errors and exceptions in the
Java language.
The root class of only exceptions : Exception
The root class of only error : Error

RuntimeExceptions its child classes & Error its child classes are unchecked
exceptions, remaining all exceptions are checked type.

The class Exception and any subclasses that are not also subclasses of
RuntimeException are checked exceptions.

Exception handling keywords:


1. try
2. catch
3. finally
4. throws
5. throw

There are two ways to handle the exceptions in java.


1) By using try-catch block.
2) By using throws keyword

Exception handling by using try–catch blocks:


Syntax:
try
{ exceptional code : it may or may not raise an exception
}
catch (Exception_Name reference_variable)
{ logics run if an exception raised in try block.
}

ex-1 : Whenever exception raised in the try block, the corresponding catch block
executed.

Application without try-catch blocks


import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ System.out.println("Application starts");
Scanner s = new Scanner(System.in);
System.out.println("Enter a num....");
int num = s.nextInt();
System.out.println(10/num);
System.out.println("rest of the application");
}
}
E:\>java Test
Application starts
Enter a num....
0
Exception in thread "main" java.lang.ArithmeticException: / by
zero

Disadvantages:
a. program terminated abnormally.
b. rest of the application not executed.

Application with try-catch blocks:


import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ System.out.println("Application starts");
Scanner s = new Scanner(System.in);
System.out.println("Enter a num....");
int num = s.nextInt();
try{
System.out.println(10/num);
}
catch(ArithmeticException ae)
{ System.out.println(10/2);
}
System.out.println("Rest of the application");
}
}
E:\>java Test
Enter a number:
0
5
Rest of the application.....

Advantages:
a. Program terminated normally
b. Rest of the application executed

ex-2 : In below example catch block is not matched hence program is terminated
abnormally.
try
{ System.out.println("sravya");
System.out.println(10/0);
}
catch(NullPointerException e)
{ System.out.println(10/2);
}

ex 3: If there is no exception in try block the corresponding catch blocks are not
checked.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
}
catch(NullPointerException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}

ex-4: In Exception handling independent try blocks declaration are not allowed.
class Test
{ public static void main(String[] args)
{ try
{ System.out.println("sravya");
}
System.out.println("rest of the app");
}
}
error: 'try' without 'catch', 'finally' or resource
declarations
ex-5: In between try-catch blocks it is not possible to declare any statements.
try
{ System.out.println(10/0);
}
System.out.println("anu");
catch(ArithmeticException e)
{ System.out.println(10/2);
}

ex-6: Once the exception raised in try block the corresponding catch block
executed.
If the exception raised in catch then it is abnormal termination.
try
{ System.out.println(10/0);
}
catch(ArithmeticException e)
{ System.out.println("ratan".charAt(12));
}

ex- 7:
If the exception raised in try block the remaining code of try block is not
executed.
Once the control is out of the try block the control never entered into try block
once again.
Don’t take normal code inside try block because no guarantee all statements in try-
block will be executed or not.

class Test
{ public static void main(String[] args)
{ try{
System.out.println("durga");
System.out.println("ratan");
System.out.println(10/0);
}
catch(ArithmeticException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}

E:\sravya>java Test
Durga
ratan
rest of the app

class Test
{ public static void main(String[] args)
{ try{
System.out.println(10/0);
System.out.println("durga");
System.out.println("ratan");
}
catch(ArithmeticException e)
{ System.out.println(10/2);
}
System.out.println("rest of the app");
}
}
E:\sravya>java Test
5
rest of the app

case 1: If the exception raised in try block : catch is matched : normal termiation
case 2: If the exception raised in try block : catch is not matched : Abnormal
termiation

case 3: If there is no exception in try then catch block is not executed.


case 4: only try block declaration is not possible
error: 'try' without 'catch', 'finally' or resource declarations

case 5: In between the try-catch blocks statemets are not allowed.


case 6: If the exception raised in try block it will check the catch block.
If the exception raised in catch block it is abnormal termination.

case 7: Once the exception raised in try block the remaining code of try block not
executed.

Category-1 : try with multiple


catch blocks
case 1 :
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter the division value");

try
{ int num = s.nextInt();
System.out.println(10/num);
System.out.println("ratan".charAt(10));
}
catch(InputMismatchException i)
{ System.out.println("Enter valid data....only integers");
}
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
catch(StringIndexOutOfBoundsException e)
{ System.out.println("durgasoft");
}
System.out.println("Rest of the application....");
}
}

case-2: lazy
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter the division value");
try
{ int num = s.nextInt();
System.out.println(10/num);
System.out.println("ratan".charAt(10));
}
catch (Exception e)
{ System.out.println("Exception info..."+e);
}
System.out.println("Rest of the application....");
}
}

case 3: The catch block order must be child to parent.


import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter the division value");

try
{ int num = s.nextInt();
System.out.println(10/num);
System.out.println("ratan".charAt(10));
}
//child to parent
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
catch(Exception e)
{ System.out.println("Exception Info..."+e);
}
System.out.println("Rest of the application....");
}
}

case 4: Parent to child :


import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("enter the division value");
try
{ int num = s.nextInt();
System.out.println(10/num);
System.out.println("ratan".charAt(10));
}
catch(Exception e)
{ System.out.println("nareshit");
}
catch (ArithmeticException ae)
{ System.out.println("Ratanit");
}
System.out.println("Rest of the application....");
}
}
in above case the parent can handle all exceptions then child no use.
error: exception ArithmeticException has already been caught

Category-2 pipe symbol java 7-version

The single catch block can handle the multiple exceptions using pipe symbol.
case 1: unchecked
catch(ArithmeticException | ClassCastException a)
catch(NumberFormatException|NullPointerException|StringIndexOutOfBoundsException a)
case 2: checked
catch(FileNotFoundException|InterruptedException a)

case 3: mixing of both checked & uncheked


catch(FileNotFoundException| ArithmeticException a)

case 4: Invalid : not possible to take both parent & child


catch(Exception | ArithmeticException a)

Category-3 try-with resources java-7

case 1:
a. Declare the resource using try block, once the try block is completed the
resource is automatically released.
b. how it is release automatically means it internally uses AutoCloseable.
E:\>javap java.lang.AutoCloseable
public interface java.lang.AutoCloseable {
public abstract void close() throws java.lang.Exception;
}
c. The close() method is invoked automatically on objects managed by the try-with-
resources statement.

ex-1:
case-1. In below code must close the scanner object using close() method.
import java.util.*;
class Test
{ public static void main(String[] args)
{ Scanner s = new Scanner(System.in);
System.out.println("Enter a number.....");
int num = s.nextInt();
System.out.println("Your number....."+num);
s.close();
}
}

case-2. Declare the resource using try block, once the try block is completed
the resource is automatically released.
import java.util.Scanner;
class Test
{ public static void main(String[] args)
{ try(Scanner s = new Scanner(System.in))
{ System.out.println("enter id");
int a = s.nextInt();
System.out.println("input value="+a);
}
}
}

Observation:
1. If the rsource is not throwing any exception then catch block not required.
try(Scanner s = new Scanner(System.in))
{ logics
}

ex-2:
import java.io.*;
class Test
{ public static void main(String[] args)
{ try(FileInputStream fis = new FileInputStream("abc.txt"))
{ System.out.println("reading data from text file");
}
catch(IOException e)
{ System.out.println("Exceptio raised....");
}
}
}
if the resource is throwing an excpetions so catch block required.
FileNotFoundException : reading the data from file
IOException : exception thrown from implicit call to close()

FileNotFoundException is a child class of IOException so taking catch block of


parent class is good.

ex-3: By using try block it is possible to declare more than one resource but every
resource is separated with semicolon.
try(Scanner s = new Scanner(System.in);
FileInputStream fis = new FileInputStream("abc.txt"))
{ //some code here
}
in multiple resources if at lease one resource throws exception then catch is
mandatory.

Category-4 posibilities of try-catch

case 1:
try{
}
catch (){
}

case 2:
try{
}
catch (){
}
fsdfsdf
sdfsdfsdf
try{
}
catch (){
}

case 3: try-with multiple catch blocks.


try{
}
catch (){
}
catch (){
}

case 4: Inside the try block possible to declare the try-catch


try
{ try
{
}
catch ()
{
}
}
catch ()
{
}

case 5:
try
{
}
catch ()
{ try
{
}
catch ()
{
}
}

case 6:
try
{ try
{
}
catch ()
{
}
}
catch ()
{ try
{
}
catch ()
{
}
}

Category-5 printing Exception information

case 1:The developer can print the exceptions msg in three ways,
1) printing reference variable
2) getMessage()
3) printStackTrace()

class Test
{ void m3()
{ try
{ System.out.println(10/0);
}
catch(ArithmeticException ae)
{ System.out.println(ae);
System.out.println(ae.getMessage());
ae.printStackTrace();
}
}
void m2()
{ m3();
}
void m1()
{ m2();
}
public static void main(String[] args)
{ new Test().m1();
}
}

E:\>java Test
java.lang.ArithmeticException: / by zero
/ by zero
java.lang.ArithmeticException: / by zero
at Test.m3(Test.java:3)
at Test.m2(Test.java:12)
at Test.m1(Test.java:15)
at Test.main(Test.java:18)

case 2: if we are not handled exception so The JVM Internally uses


printStackTrace() method to print exception information.

finally
=======
//Application without finally
try
{ connection open
tx1
tx2
}
catch (exception-name)
{
}
connection closed

case 1: connection open : both trasaction are success : Normal termination :


connection is closed
case 2: connection open : first transaction is fail : catch block is matched :
normal termination : connection is closed
case 3: connection open : second transaction is fail: catch block is not
matched :abnormal termination : connection is not closed

Note: To close the connection both normal & abnormal cases use finally block
because the finally block code executed both normal & abnormal cases.

//Application with finally


try
{ connection open
tx1
tx2
}
catch ()
{ handle the exception....
}
finally{
conection close
}

Note: To release the resources both normal & abnormal cases use finally block.
file closing.
Scanner object closing.
Connection closing.

Case 1:NT
try
{ System.out.println("try");
}
catch (ArithmeticException ae)
{ System.out.println("catch");
}
finally
{ System.out.println("finally");
}

case 2: NT
try
{ System.out.println(10/0);
}
catch (ArithmeticException ae)
{ System.out.println("catch");
}
finally
{ System.out.println("finally");
}

case 3:ABT
try
{ System.out.println(10/0);
}
catch (NullPointerException ae)
{ System.out.println("catch");
}
finally
{ System.out.println("finally");
}

case 4: ABT
try
{ System.out.println(10/0);
}
catch (ArithmeticException ae)
{ System.out.println(10/0);
}
finally
{ System.out.println("finally");
}

case 5: ABT
try
{ System.out.println("try");
}
catch(ArithmeticException ae)
{ System.out.println("catch");
}
finally
{ System.out.println(10/0);
}

case 6:
try
{ System.out.println("try");
}
finally
{ System.out.println("finally");
}

Note:
try-catch : valid
try-with resources : valid
try-finally : valid

only try : Invalid


only catch : Invalid
only finally : Invalid

try-catch : Valid
try-finally : Valid
try-catch-finally : Valid
try-catch-catch : Valid
try-catch-catch-finally : Valid

catch-finally : Invalid
try-finally-finally : Invalid
try-finally-catch : Invalid
try-catch-finally-catch : Invalid

catch-try-finally : Invalid
try-catch-finally-finally : Invalid
try-try-catch-finally : Invalid

In two cases finally block won’t be executed


Case 1: whenever the control is entered into try block then only finally
block will be executed otherwise it is not executed
class Test
{ public static void main(String[] args)
{ System.out.println(10/0);
try
{ System.out.println("ratan");
}
finally
{ System.out.println("finally block");
}
System.out.println("rest of the code");
}
}

case 2:
class Test
{ public static void main(String[] args)
{
try
{ System.out.println("ratan");
System.exit(0);
}
finally
{ System.out.println("finally block");
}
System.out.println("rest of the code");
}
}

public static void exit(int status)


Terminates the currently running Java Virtual Machine. The argument serves as a
status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns
normally.
The call System.exit(n) is effectively equivalent to the call:
Runtime.getRuntime().exit(n)

interview :
case 1:
class Test
{ public static void main(String[] args)
{ try
{ System.out.println(10/0);
}
catch(Exception e)
{ System.out.println("ratan".charAt(20));
}
finally
{ int[] a={10,20,30};
System.out.println(a[9]);
}
}
}

case 2:
class Test
{ int m1()
{ try
{ return 10;
}
catch(Exception e)
{ return 20;
}
finally
{ return 30;
}
}
public static void main(String[] args)
{ int a = new Test().m1();
System.out.println("return value="+a);
}
}

st-1 st-2
try
{ st-3 st-4
try
{ st-5 st-6
}
catch ()
{ st-7 st-8
}
}
catch ()
{ st-9 st-10
try
{ st-11 st-12
}
catch ()
{ st-13
st-14
}
}
finally
{ st-15 st-16
}
st-17 st-18

case 1: no exception in above example.


1,2,3,4,5,6,15,16,17,18 Normal termination.

case 2: exception raise in st-2


1 Abnormal termination

case 3: exp raised in st-3 catch is matched.


1,2,9,10,11,12,15,16,17,18 normal termiatio

case 4: exp raised in st-4 catch is not matched.


1,2,3,15,16 abrnormal termination

case 5: exp raised in st-5 catch is matched.


1,2,3,4,7,8,15,16,17,18 normal termination

case 6: exp raised in st-6 inner catch is not matched but outer catch is matched.
1,2,3,4,5,9,10,11,12,15,16,17,18 normal termination

case 7: exp raised in st-16

case 8: exp raised in st-18

throws keyword
==============

There are two ways to handle the exceptions,


a. using try-catch : to handle the exception exception
b. using throws : to deligate the exception to caller method

case 1:
import java.io.*;
class Test
{ void studentInfo()throws FileNotFoundException
{ System.out.println("Veera information....");
FileInputStream fis = new FileInputStream("abc.txt");
}
void hod()throws FileNotFoundException
{ studentInfo();
}
void principal()
{ try{hod();}
catch(FileNotFoundException e)
{System.out.println("file is not present...");}
}
void officeBoy()
{ principal();
}
public static void main(String[] args)
{ Test t = new Test();
t.officeBoy();
}
}

case 2:
import java.io.*;
class Test
{ void studentInfo()throws FileNotFoundException
{ System.out.println("Veera information....");
FileInputStream fis = new FileInputStream("abc.txt");
}
void hod()throws FileNotFoundException
{ studentInfo();
}
void principal()throws FileNotFoundException
{ hod();
}
void officeBoy()throws FileNotFoundException
{ principal();
}
public static void main(String[] args) throws FileNotFoundException
{ Test t = new Test();
t.officeBoy();
}
}

If the main throws the exception then JVM is responsible to handle the exception.

ex 3: One method can throws multiple exceptions


import java.io.*;
class Test
{ void m2()throws FileNotFoundException,InterruptedException
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()
{ try
{ m2();
}
catch(FileNotFoundException | InterruptedException f)
{ f.printStackTrace();
}
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}

ex-4: use the root cls to throws all exceptions.


import java.io.*;
class Test
{ void m2()throws Exception
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()
{ try
{ m2();
}
catch(Exception f)
{ f.printStackTrace();
}
}
public static void main(String[] args)
{ Test t = new Test();
t.m1();
}
}

Observation: The method can throws parent & child exeptions but it is not
recommanded.
void m2()throws InterruptedException,Exception
{
}

ex-5:
import java.io.*;
class Test
{ void m2()throws FileNotFoundException,InterruptedException
{ FileInputStream fis = new FileInputStream("abc.txt");
Thread.sleep(2000);
System.out.println("Exceptions are handled");
}
void m1()throws InterruptedException
{ try
{ m2();
}
catch(FileNotFoundException f)
{ f.printStackTrace();
}
}
public static void main(String[] args)
{ Test t = new Test();
try
{ t.m1();
}
catch (InterruptedException i)
{ i.printStackTrace();
}
}
}

ex-6: Exception Propagation.


class Test
{ void m3()
{ System.out.println(10/0);
}
void m2()
{ m3();
}
void m1()
{ try
{ m2();
}
catch(ArithmeticException ae)
{ System.out.println("Exception handled...");
}
}
public static void main(String[] args)
{ new Test().m1();
}
}

In above example the exception raised in m3() method but it is not handled so it
is propagated to m2() method.
Here the m2() method is not handled exception so it is propagated to m1().
In above example m1() is handled exception.

Note: only the unchecked Exceptions are propagated automatically but not checked.
The checked exceptions are propagated using throws keyword.

Note: using throws it is possible to propagate unchecked exceptions but it is not


recommanded.

throw

ex: here we are throwing predefiend exception which is not recommanded.


Because the predefined exceptions are having fixed meaning.

import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new ArithmeticException("your not eligible try after
sometime...");
}
}
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age = s.nextInt();
Test.validate(age);
}
}
E:\>java Test
please enter your age
12
Exception in thread "main" java.lang.ArithmeticException: your not eligible try
after sometime...

Userdefiend exception

There are two types of userdefined exceptions,


1. userdefined checked exception.
a. default constructor : Exception without description
b. params constructor : Exception with description.

class InvalidAgeException extends Exception


{
}

2. userdefined un-checked exception


a. default constructor : Exception without description
b. params constructor : Exception with description.

class InvalidAgeException extends RuntimeException


{
}

ex-1: userdefined unchecked exception : with default constructor : without


discription.
step 1: create the userdefined exception
class InvalidAgeException extends RuntimeException
{ //default cons
}

step 2: use that exception in our project.


import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new InvalidAgeException();
}
}
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age = s.nextInt();
Test.validate(age);
}
}
E:\>java Test
please enter your age
12
Exception in thread "main" InvalidAgeException

ex-2: userdefined unchecked exception : with params constructor : with description.


step 1: create the exception
class InvalidAgeException extends RuntimeException
{ InvalidAgeException(String msg)
{ super(msg);// calling the parent constructor by passing our
information.....
}
}

step 2 : use the exception in our project


import java.util.*;
class Test
{ static void validate(int age)
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new InvalidAgeException("Your not aligible try after some
time....");
}
}
public static void main(String[] args)
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age = s.nextInt();
Test.validate(age);
}
}
E:\>java Test
please enter your age
13
Exception in thread "main" InvalidAgeException: Your not aligible try after some
time....

ex: userdefined checked exception : with params constructor : with description.


step 1: create the exception
class InvalidAgeException extends Exception
{ InvalidAgeException(String str)
{ super(str);
}
}

step 2 : use the exception in our project


import java.util.*;
class Test
{ static void validate(int age) throws InvalidAgeException
{ if (age>18)
{ System.out.println("eligible for mrg");
}
else
{ throw new InvalidAgeException("u r not eliible to mrg");
}
}
public static void main(String[] args) throws InvalidAgeException
{ Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age = s.nextInt();
Test.validate(age);
}
}

Note: using throw keyword we can throw predefined exceptions & userdefined
exception.
But throwing predefined exceptions are not recommanded because predefined
exceptions are having fixed meaning.

try : it contains exceptional code it may or maynot raise an


exception.
catch : these logics are executed when exception raised in try block.
finally : These logics are executed both normal & abnormal cases.
throws : To delegate the responsibility of exception handling to
caller methods.
throw : Used to throw the exception.

Assignmen-1 : java.lang.NoClassDefFoundError vs java.lang.ClassNotFoundException

Assignment-2: can we create the userdefined errors.


yes : write the example
no : no example

Assignment-3: create the un-checked exception.


TooYoungException : wiht description : "your kid try after some
time"
TooOldException : with description : "your old man not
eligible to mrg"
In Application Take the input from end user
age <18 : throw TooYoungException
age >35 : throw TooOldException
age b/w 18 to 30 : eligible for mrg enjoy.

Assignment-4: When we will get NullPointerException. write multiple cases.

You might also like