SlideShare a Scribd company logo
PROGRAMMING IN JAVA
A. SIVASANKARI
ASSISTANT PROFESSOR
DEPARTMENT OF COMPUTER APPLICATION
SHANMUGA INDUSTRIES ARTS AND SCIENCE
COLLEGE,
TIRUVANNAMALAI. 606601.
Email: sivasankaridkm@gmail.com
PROGRAMMING IN JAVA
UNIT - 3
PART-I
 STRING
 STRING HANDLING
 STRING METHODS
 STRING BUFFER CLASS
 STRING BUILDER
 STRING TOKENIZER
CLASS
 EXCEPTION HANDLING
A. SIVASANKARI - SIASC-TVM UNIT-3
STRING
DEFINITION OF STRING CLASS
• Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.
• The Java platform provides the String class to create and manipulate strings.
• Creating Strings
• The most direct way to create a string is to write
• String greeting = "Hello world!";
• Whenever it encounters a string literal in your code, the compiler creates a String object with
its value in this case, "Hello world!'.
• EXAMPLE
• public class StringDemo
• {
• public static void main(String args[])
• {
• char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
• String helloString = new String(helloArray);
• System.out.println( helloString );
• }}
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING REVERCE
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
Java toString() method
• If we want to represent any object as a string, toString() method comes into existence.
• The toString() method returns the string representation of the object.
• If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.
Advantage of Java toString() method
• By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.
Understanding problem without toString() method
• class Student{
• int rollno;
• String name;
• String city;
• Student(int rollno, String name, String city){
• this.rollno=rollno;
• this.name=name;
• this.city=city;
• }
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
• public static void main(String args[]){
• Student s1=new Student(101,"Raj","lucknow");
• Student s2=new Student(102,"Vijay","ghaziabad");
• System.out.println(s1); //compiler writes here s1.toString()
• System.out.println(s2); //compiler writes here s2.toString()
• }
• }
OUTPUT:
• Student@1fee6fc
• Student@1eed786
Understanding problem toString() method
• public class Test {
• public static void main(String args[]) {
• Integer x = 5;
• System.out.println(x.toString());
• System.out.println(Integer.toString(12));
• }
• }
OUTPUT:
• 5
• 12
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING AND STRING BUFFER
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING BUILDER
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
STRING AND STRING BUFFER AND STRING BUILDER
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
EXCEPTION HANDLING
• An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
• An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out
of memory.
• Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
• Based on these, we have three categories of Exceptions. We need to understand them to
know how exception handling works in Java.
• Checked exceptions − A checked exception is an exception that is checked (notified) by the
compiler at compilation-time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer should take care of (handle) these
exceptions.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
• For example, if we use FileReader class in our program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Example
• import java.io.File;
• import java.io.FileReader;
• public class FilenotFound_Demo {
• public static void main(String args[]) {
• File file = new File("E://file.txt");
• FileReader fr = new FileReader(file); }}
• If we try to compile the above program, you will get the following exceptions.
Output
• C:>javac FilenotFound_Demo.javaFilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown FileReader fr = new
FileReader(file); ^1 error
• Note − Since the methods read() and close() of FileReader class throws IOException, we can
observe that the compiler notifies to handle IOException, along with FileNotFoundException.
• Unchecked exceptions − An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
EXCEPTION HIERARCHY
• All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
• Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of memory. Normally, programs cannot recover from
errors.
• The Exception class has two main subclasses: IOException class and RuntimeException
Class
PROGRAMMING IN JAVA
1. TRY
2. CATCH
3. THROW
4. THROWS
5. FINALLY
A. SIVASANKARI - SIASC-TVM
Sr.No. EXCEPTIONS METHODS & DESCRIPTION
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the
Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString() [Returns the name of the class concatenated with the result of
getMessage().
4 public void printStackTrace() [Prints the result of toString() along with the stack trace to
System.err, the error output stream.]
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the
top of the call stack, and the last element in the array represents the method at the bottom of the call
stack.
6 public Throwable fillInStackTrace() [Fills the stack trace of this Throwable object with the
current stack trace, adding to any previous information in the stack trace.]
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
1. TRY -CATCHING EXCEPTIONS
• A method catches an exception using a combination of the try and catch keywords.
• A try/catch block is placed around the code that might generate an exception.
• Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following
SYNTAX
• try {
• // Protected code
• }
• catch (ExceptionName e1)
• { // Catch block
• }
• The code which is prone to exceptions is placed in the try block. When an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should
be immediately followed either by a catch block or finally block.
• A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
EXAMPLE
// File Name : ExcepTest.java
• import java.io.*;
• public class ExcepTest
• {
• public static void main(String args[]) {
• try {
• int a[] = new int[2];
• System.out.println("Access element three :" + a[3]);
• }
• catch (ArrayIndexOutOfBoundsException e)
• { System.out.println("Exception thrown :" + e);
• }
• System.out.println("Out of the block"); }}
OUTPUT
• Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
2. MULTIPLE CATCH BLOCKS
• A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks like the following
• Syntax
• try {
• // Protected code}
• catch (ExceptionType1 e1)
• { // Catch block}
• catch (ExceptionType2 e2)
• { // Catch block}
• catch (ExceptionType3 e3)
• { // Catch block}
EXAMPLE
• try {
• file = new FileInputStream(fileName);
• x = (byte) file.read();}
• catch (IOException i) {
• i.printStackTrace();
• return -1;}
• catch (FileNotFoundException f) // Not valid!
• { f.printStackTrace();
• return -1;}
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
3. THE THROWS/THROW
• If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's
signature.
• You can throw an exception, either a newly instantiated one or an exception that
you just caught, by using the throw keyword.
• Try to understand the difference between throws and throw keywords, throws is
used to postpone the handling of a checked exception and throw is used to invoke
an exception explicitly.
• The following method declares that it throws a RemoteException
EXAMPLE
• import java.io.*;
• public class className {
• public void deposit(double amount) throws RemoteException
• { // Method implementation
• throw new RemoteException();
• } // Remainder of class definition
• }
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
4. THE FINALLY BLOCK
• The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception.
• Using a finally block allows you to run any clean-up-type statements that you want to
execute, no matter what happens in the protected code.
• A finally block appears at the end of the catch blocks and has the following syntax −
SYNTAX
• try { // Protected code}
• catch (ExceptionType1 e1)
• { // Catch block}
• catch (ExceptionType2 e2)
• {
• // Catch block} catch (ExceptionType3 e3)
• { // Catch block}
• finally
• { // The finally block always executes.
• }
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
EXAMPLE
• public class ExcepTest {
• public static void main(String args[]) {
• int a[] = new int[2];
• try {
• System.out.println("Access element three :" + a[3]);
• }
• catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("Exception thrown :" + e); }
• finally { a[0] = 6;
• System.out.println("First element value: " + a[0]);
• System.out.println("The finally statement is
executed");}
• }}
OUTPUT
• Exception thrown
:java.lang.ArrayIndexOutOfBoundsException: 3
• First element value: 6
• The finally statement is executed
PROGRAMMING IN JAVA
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
THROW AND THROWS
A. SIVASANKARI - SIASC-TVM
PROGRAMMING IN JAVA
TRY ,CATCH ,THROW AND THROWS
A. SIVASANKARI - SIASC-TVM
A. SIVASANKARI - SIASC-TVM

More Related Content

PPTX
Java unit1 a- History of Java to string
PPTX
PROGRAMMING IN JAVA- unit 4-part I
PPTX
PROGRAMMING IN JAVA-unit 3-part II
PPTX
PROGRAMMING IN JAVA
PPTX
PROGRAMMING IN JAVA -unit 5 -part I
PPTX
PROGRAMMING IN JAVA- unit 4-part II
PPTX
PROGRAMMING IN JAVA- unit 5-part II
PDF
JAVA BOOK BY SIVASANKARI
Java unit1 a- History of Java to string
PROGRAMMING IN JAVA- unit 4-part I
PROGRAMMING IN JAVA-unit 3-part II
PROGRAMMING IN JAVA
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 5-part II
JAVA BOOK BY SIVASANKARI

What's hot (17)

PPT
Java essential notes
PPTX
Advance java prasentation
PPTX
Introduction to java
PPT
Java basic introduction
PPTX
Java 101 Intro to Java Programming
PDF
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
PPT
Basic java part_ii
PPTX
PDF
Java basics notes
PPT
Presentation on java
PDF
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
PDF
Introduction to Java Programming
PPTX
Java basic-tutorial for beginners
PDF
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
PPTX
Java 101
PDF
Core Java
PPTX
Core Java
Java essential notes
Advance java prasentation
Introduction to java
Java basic introduction
Java 101 Intro to Java Programming
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Basic java part_ii
Java basics notes
Presentation on java
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
Introduction to Java Programming
Java basic-tutorial for beginners
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java 101
Core Java
Core Java
Ad

Similar to PROGRAMMING IN JAVA (20)

PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
Java history, versions, types of errors and exception, quiz
DOCX
What is an exception in java?
PDF
Java exceptions
PPTX
UNIT III 2021R.pptx
PPTX
UNIT III 2021R.pptx
PPTX
OBJECT ORIENTED PROGRAMMING STRUCU1.pptx
PPT
exception handling in java.ppt
PPTX
using Java Exception Handling in Java.pptx
PPTX
Packages and Java Library: Introduction, Defining Package, Importing Packages...
PPTX
Packages and Java Library: Introduction, Defining Package, Importing Packages...
PPTX
Pi j4.2 software-reliability
PPTX
Exception handling in java
PPT
Exception handling
PPTX
Exception handling, Stream Classes, Multithread Programming
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
PPT
Java exception
PPTX
Java programming-Event Handling
PPT
Exception Handling in java masters of computer application
PPS
Java Exception handling
Ch-1_5.pdf this is java tutorials for all
Java history, versions, types of errors and exception, quiz
What is an exception in java?
Java exceptions
UNIT III 2021R.pptx
UNIT III 2021R.pptx
OBJECT ORIENTED PROGRAMMING STRUCU1.pptx
exception handling in java.ppt
using Java Exception Handling in Java.pptx
Packages and Java Library: Introduction, Defining Package, Importing Packages...
Packages and Java Library: Introduction, Defining Package, Importing Packages...
Pi j4.2 software-reliability
Exception handling in java
Exception handling
Exception handling, Stream Classes, Multithread Programming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
Java exception
Java programming-Event Handling
Exception Handling in java masters of computer application
Java Exception handling
Ad

More from SivaSankari36 (6)

PDF
DATA STRUCTURE BY SIVASANKARI
PDF
CLOUD COMPUTING BY SIVASANKARI
PDF
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
PDF
MOBILE COMPUTING BY SIVASANKARI
PPTX
Functional MRI using Apache Spark in Big Data Application
PPTX
Java unit1 b- Java Operators to Methods
DATA STRUCTURE BY SIVASANKARI
CLOUD COMPUTING BY SIVASANKARI
MOBILE APPLICATIONS DEVELOPMENT -ANDROID BY SIVASANKARI
MOBILE COMPUTING BY SIVASANKARI
Functional MRI using Apache Spark in Big Data Application
Java unit1 b- Java Operators to Methods

Recently uploaded (20)

PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
RMMM.pdf make it easy to upload and study
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Cell Structure & Organelles in detailed.
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
Pharma ospi slides which help in ospi learning
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
VCE English Exam - Section C Student Revision Booklet
Yogi Goddess Pres Conference Studio Updates
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O7-L3 Supply Chain Operations - ICLT Program
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
RMMM.pdf make it easy to upload and study
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
01-Introduction-to-Information-Management.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Cell Structure & Organelles in detailed.
Orientation - ARALprogram of Deped to the Parents.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
human mycosis Human fungal infections are called human mycosis..pptx
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Pharma ospi slides which help in ospi learning
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
VCE English Exam - Section C Student Revision Booklet

PROGRAMMING IN JAVA

  • 1. PROGRAMMING IN JAVA A. SIVASANKARI ASSISTANT PROFESSOR DEPARTMENT OF COMPUTER APPLICATION SHANMUGA INDUSTRIES ARTS AND SCIENCE COLLEGE, TIRUVANNAMALAI. 606601. Email: [email protected]
  • 2. PROGRAMMING IN JAVA UNIT - 3 PART-I  STRING  STRING HANDLING  STRING METHODS  STRING BUFFER CLASS  STRING BUILDER  STRING TOKENIZER CLASS  EXCEPTION HANDLING A. SIVASANKARI - SIASC-TVM UNIT-3
  • 3. STRING DEFINITION OF STRING CLASS • Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. • The Java platform provides the String class to create and manipulate strings. • Creating Strings • The most direct way to create a string is to write • String greeting = "Hello world!"; • Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'. • EXAMPLE • public class StringDemo • { • public static void main(String args[]) • { • char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; • String helloString = new String(helloArray); • System.out.println( helloString ); • }} PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM STRING REVERCE
  • 4. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 5. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 6. Java toString() method • If we want to represent any object as a string, toString() method comes into existence. • The toString() method returns the string representation of the object. • If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation. Advantage of Java toString() method • By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code. Understanding problem without toString() method • class Student{ • int rollno; • String name; • String city; • Student(int rollno, String name, String city){ • this.rollno=rollno; • this.name=name; • this.city=city; • } PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 7. • public static void main(String args[]){ • Student s1=new Student(101,"Raj","lucknow"); • Student s2=new Student(102,"Vijay","ghaziabad"); • System.out.println(s1); //compiler writes here s1.toString() • System.out.println(s2); //compiler writes here s2.toString() • } • } OUTPUT: • Student@1fee6fc • Student@1eed786 Understanding problem toString() method • public class Test { • public static void main(String args[]) { • Integer x = 5; • System.out.println(x.toString()); • System.out.println(Integer.toString(12)); • } • } OUTPUT: • 5 • 12 PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 8. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 9. STRING AND STRING BUFFER PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 10. STRING BUILDER PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 11. STRING AND STRING BUFFER AND STRING BUILDER PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 12. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 13. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 14. EXCEPTION HANDLING • An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. • An exception can occur for many different reasons. Following are some scenarios where an exception occurs. • A user has entered an invalid data. • A file that needs to be opened cannot be found. • A network connection has been lost in the middle of communications or the JVM has run out of memory. • Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. • Based on these, we have three categories of Exceptions. We need to understand them to know how exception handling works in Java. • Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 15. • For example, if we use FileReader class in our program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception. Example • import java.io.File; • import java.io.FileReader; • public class FilenotFound_Demo { • public static void main(String args[]) { • File file = new File("E://file.txt"); • FileReader fr = new FileReader(file); }} • If we try to compile the above program, you will get the following exceptions. Output • C:>javac FilenotFound_Demo.javaFilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^1 error • Note − Since the methods read() and close() of FileReader class throws IOException, we can observe that the compiler notifies to handle IOException, along with FileNotFoundException. • Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 16. EXCEPTION HIERARCHY • All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. • Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is out of memory. Normally, programs cannot recover from errors. • The Exception class has two main subclasses: IOException class and RuntimeException Class PROGRAMMING IN JAVA 1. TRY 2. CATCH 3. THROW 4. THROWS 5. FINALLY A. SIVASANKARI - SIASC-TVM
  • 17. Sr.No. EXCEPTIONS METHODS & DESCRIPTION 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. 2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 3 public String toString() [Returns the name of the class concatenated with the result of getMessage(). 4 public void printStackTrace() [Prints the result of toString() along with the stack trace to System.err, the error output stream.] 5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. 6 public Throwable fillInStackTrace() [Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.] PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 18. 1. TRY -CATCHING EXCEPTIONS • A method catches an exception using a combination of the try and catch keywords. • A try/catch block is placed around the code that might generate an exception. • Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following SYNTAX • try { • // Protected code • } • catch (ExceptionName e1) • { // Catch block • } • The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block. • A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 19. EXAMPLE // File Name : ExcepTest.java • import java.io.*; • public class ExcepTest • { • public static void main(String args[]) { • try { • int a[] = new int[2]; • System.out.println("Access element three :" + a[3]); • } • catch (ArrayIndexOutOfBoundsException e) • { System.out.println("Exception thrown :" + e); • } • System.out.println("Out of the block"); }} OUTPUT • Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 20. 2. MULTIPLE CATCH BLOCKS • A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following • Syntax • try { • // Protected code} • catch (ExceptionType1 e1) • { // Catch block} • catch (ExceptionType2 e2) • { // Catch block} • catch (ExceptionType3 e3) • { // Catch block} EXAMPLE • try { • file = new FileInputStream(fileName); • x = (byte) file.read();} • catch (IOException i) { • i.printStackTrace(); • return -1;} • catch (FileNotFoundException f) // Not valid! • { f.printStackTrace(); • return -1;} PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 21. 3. THE THROWS/THROW • If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. • You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. • Try to understand the difference between throws and throw keywords, throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly. • The following method declares that it throws a RemoteException EXAMPLE • import java.io.*; • public class className { • public void deposit(double amount) throws RemoteException • { // Method implementation • throw new RemoteException(); • } // Remainder of class definition • } PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 22. 4. THE FINALLY BLOCK • The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. • Using a finally block allows you to run any clean-up-type statements that you want to execute, no matter what happens in the protected code. • A finally block appears at the end of the catch blocks and has the following syntax − SYNTAX • try { // Protected code} • catch (ExceptionType1 e1) • { // Catch block} • catch (ExceptionType2 e2) • { • // Catch block} catch (ExceptionType3 e3) • { // Catch block} • finally • { // The finally block always executes. • } PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 23. EXAMPLE • public class ExcepTest { • public static void main(String args[]) { • int a[] = new int[2]; • try { • System.out.println("Access element three :" + a[3]); • } • catch (ArrayIndexOutOfBoundsException e) { • System.out.println("Exception thrown :" + e); } • finally { a[0] = 6; • System.out.println("First element value: " + a[0]); • System.out.println("The finally statement is executed");} • }} OUTPUT • Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 • First element value: 6 • The finally statement is executed PROGRAMMING IN JAVA A. SIVASANKARI - SIASC-TVM
  • 24. PROGRAMMING IN JAVA THROW AND THROWS A. SIVASANKARI - SIASC-TVM
  • 25. PROGRAMMING IN JAVA TRY ,CATCH ,THROW AND THROWS A. SIVASANKARI - SIASC-TVM
  • 26. A. SIVASANKARI - SIASC-TVM