SlideShare a Scribd company logo
1 of 21
ADHIYAMAAN COLLEGE OF ENGINEERING (AUTONOMOUS)
DEPARTMENT OF INFORMATION TECHNOLOGY
Mrs.S.Sujatha ,ME,
Assistant Professor,
Dept of Information Technology,
Adhiyamaan College of Engineering, Hosur
UNIT-II
EXCEPTION
EXCEPTION
• An exception is an unwanted or unexpected
event, which occurs during the execution of a
program i.e at run time, that disrupts the
normal flow of the program’s instructions.
• There are two type of exception
– Checked exception
– Unchecked Exception
CHECKED EXCEPTION
• All exceptions other than Runtime Exceptions
are known as Checked exceptions as the
compiler checks them during compilation to
see whether the programmer has handled
them or not.
• If these exceptions are not handled/declared
in the program, you will get compilation error.
• For example, SQLException, IOException,
ClassNotFoundException etc.
EXAMPLE
Class file
{
public static void main(String args[])
{
file f=new file(“e://file.txt”);
fileReader fr =new fileReader(file);
}
}
o/p:
error
UNCHECKED EXCEPTION
• Runtime Exceptions are also known as Unchecked
Exceptions.
• These exceptions are not checked at compile-
time so compiler does not check whether the
programmer has handled them or not but it’s the
responsibility of the programmer to handle these
exceptions and provide a safe exit.
• For example, ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException etc.
EXAMPLE
Class example
{
Public static void main(String args[])
{
int a[]={2,3,4};
system.out.println(+a[4]);
}
}
o/p
error
HANDLING EXCEPTION
• Find the problem(hit the exception)
• Inform the error has occur(throw)
• Recevied error(catch)
• Take action
• Close all file and threads
SYNTAX
Try
{
Body of try block;
}
Catch(Exception e)
{
Handle statement;
}
Using try -catch
• The try block contains set of statements where an
exception can occur.
• A try block is always followed by a catch block, which
handles the exception that occurs in associated try
block.
• A try block must be followed by catch blocks or finally
block or both.
SYNTAX
try{
//statements that may cause an exception
}
catch
• A catch block is where you handle the exceptions, this
block must follow the try block. A single try block can
have several catch blocks associated with it
Try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
EXAMPLE
Class Example1
{
public static void main(String args[])
{
int num1, num2;
try
{
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e)
{
System.out.println("You should not divide a number by zero");
}
}
}
MULTIPLE CATCH
• A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler.
• SYNTAX
try {
// Protected code
}
catch (ExceptionType1 e1)
{ // Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
catch (ExceptionType3 e3) {
// Catch block
}
EXAMPLE
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[6]=30/2;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
}
}
Throw vs throws
• Throws clause is used to declare an exception, which
means it works similar to the try-catch block. On the other
hand throw keyword is used to throw an exception
explicitly.
• If we see syntax wise than throw is followed by an instance
of Exception class and throws is followed by exception class
names.
• Throw keyword is used in the method body to throw an
exception, while throws is used in method signature to
declare the exceptions that can occur in the statements
present in the method.
• throw one exception at a time but you can handle multiple
exceptions by declaring them using throws keyword.
Throw Example
public class Example1
{
void checkAge(int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else System.out.println("Eligible for voting");
}
public static void main(String args[])
{
Example1 obj = new Example1();
obj.checkAge(13);
System.out.println("End Of Program");
} }
Throws Example
public class Example1
{
int division(int a, int b) throws ArithmeticException
{
int t = a/b;
return t;
}
public static void main(String args[])
{
Example1 obj = new Example1();
try
{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e)
{
System.out.println("You shouldn't divide number by zero");
}
}
}
Finally class
• The finally statement lets you execute code, after try...catch
public class Main
{
public static void main(String[] args)
{
try
{
int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println("Something went wrong.");
}
finally
{
System.out.println("The 'try catch' is finished."); } } }
Exception type
• Built in exception
• User defined exaception
– Extend the exception class to create user defined
exception.
• Class myexception extend exception
– Intialize user defined exception class by creating
constructor
• Myexception()
{
}
– To raise a exception create object
• Myexception obj=new myexception()
example
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
java.pptx

More Related Content

Similar to java.pptx

Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allHayomeTakele
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 

Similar to java.pptx (20)

Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java unit3
Java unit3Java unit3
Java unit3
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 

Recently uploaded

(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 

Recently uploaded (20)

(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 

java.pptx

  • 1. ADHIYAMAAN COLLEGE OF ENGINEERING (AUTONOMOUS) DEPARTMENT OF INFORMATION TECHNOLOGY Mrs.S.Sujatha ,ME, Assistant Professor, Dept of Information Technology, Adhiyamaan College of Engineering, Hosur
  • 3. EXCEPTION • An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. • There are two type of exception – Checked exception – Unchecked Exception
  • 4. CHECKED EXCEPTION • All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. • If these exceptions are not handled/declared in the program, you will get compilation error. • For example, SQLException, IOException, ClassNotFoundException etc.
  • 5. EXAMPLE Class file { public static void main(String args[]) { file f=new file(“e://file.txt”); fileReader fr =new fileReader(file); } } o/p: error
  • 6. UNCHECKED EXCEPTION • Runtime Exceptions are also known as Unchecked Exceptions. • These exceptions are not checked at compile- time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. • For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
  • 7. EXAMPLE Class example { Public static void main(String args[]) { int a[]={2,3,4}; system.out.println(+a[4]); } } o/p error
  • 8. HANDLING EXCEPTION • Find the problem(hit the exception) • Inform the error has occur(throw) • Recevied error(catch) • Take action • Close all file and threads SYNTAX Try { Body of try block; } Catch(Exception e) { Handle statement; }
  • 9. Using try -catch • The try block contains set of statements where an exception can occur. • A try block is always followed by a catch block, which handles the exception that occurs in associated try block. • A try block must be followed by catch blocks or finally block or both. SYNTAX try{ //statements that may cause an exception }
  • 10. catch • A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it Try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code }
  • 11. EXAMPLE Class Example1 { public static void main(String args[]) { int num1, num2; try { num1 = 0; num2 = 62 / num1; System.out.println(num2); System.out.println("Hey I'm at the end of try block"); } catch (ArithmeticException e) { System.out.println("You should not divide a number by zero"); } } }
  • 12. MULTIPLE CATCH • A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler. • SYNTAX try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }
  • 13. EXAMPLE public class MultipleCatchBlock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[6]=30/2; } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } } }
  • 14. Throw vs throws • Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly. • If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names. • Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method. • throw one exception at a time but you can handle multiple exceptions by declaring them using throws keyword.
  • 15. Throw Example public class Example1 { void checkAge(int age) { if(age<18) throw new ArithmeticException("Not Eligible for voting"); else System.out.println("Eligible for voting"); } public static void main(String args[]) { Example1 obj = new Example1(); obj.checkAge(13); System.out.println("End Of Program"); } }
  • 16. Throws Example public class Example1 { int division(int a, int b) throws ArithmeticException { int t = a/b; return t; } public static void main(String args[]) { Example1 obj = new Example1(); try { System.out.println(obj.division(15,0)); } catch(ArithmeticException e) { System.out.println("You shouldn't divide number by zero"); } } }
  • 17. Finally class • The finally statement lets you execute code, after try...catch public class Main { public static void main(String[] args) { try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println("Something went wrong."); } finally { System.out.println("The 'try catch' is finished."); } } }
  • 18. Exception type • Built in exception
  • 19. • User defined exaception – Extend the exception class to create user defined exception. • Class myexception extend exception – Intialize user defined exception class by creating constructor • Myexception() { } – To raise a exception create object • Myexception obj=new myexception()
  • 20. example class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class TestCustomException1{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); } }