Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Unit 3

The document provides an overview of exception handling in Java, detailing its fundamentals, types of exceptions, and the use of keywords like try, catch, throw, throws, and finally. It also covers I/O basics, including reading console input and writing output, as well as methods for file handling and creating custom exceptions. Additionally, it outlines various ways to read input from the console using BufferedReader, Scanner, Console, and command line arguments.

Uploaded by

2022ece.r109
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Unit 3

The document provides an overview of exception handling in Java, detailing its fundamentals, types of exceptions, and the use of keywords like try, catch, throw, throws, and finally. It also covers I/O basics, including reading console input and writing output, as well as methods for file handling and creating custom exceptions. Additionally, it outlines various ways to read input from the console using BufferedReader, Scanner, Console, and command line arguments.

Uploaded by

2022ece.r109
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

CONCEPTS:

Exception handling :
• Exception handling Fundamentals, Exception types
• Uncaught exceptions, using try and catch
• multiple catch clauses, nested try statements
• throw, throws and finally
• built- in exceptions
• creating own exception sub classes

I/O and Other Topics :


• I/O Basics
• Reading console Input and Writing Console Output
• The PrintWriter Class
• Reading and writing Files
• Automatically closing a File,
• Enumerations , type wrappers
COURSE: OOPJ UNIT: 3 Pg. 1
EXCEPTION HANDLING FUNDAMENTALS

 The exception handling in java is one of the


powerful mechanism to handle the runtime errors so that normal
flow of the application can be maintained.

WHAT IS EXCEPTION
 Dictionary Meaning: Exception is an abnormal condition.
 In java, exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.

WHAT IS EXCEPTION HANDLING:


• Exception Handling is a mechanism to handle runtime errors such
as ClassNotFound, IO, SQL, Remote etc.

COURSE: OOPJ UNIT: 3 Pg. 2


EXCEPTION HANDLING FUNDAMENTALS

ADVANTAGE OF EXCEPTION HANDLING:


• The core advantage of exception handling is to maintain the
normal flow of the application.
• Meaningful Error Reporting.
KEYWORDS:
• Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally

COURSE: OOPJ UNIT: 3 Pg. 3


THE GENERAL FORM OF AN EXCEPTION-HANDLING BLOCK
try
{
} / / block of code to monitor for errors
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.

COURSE: OOPJ UNIT: 3 Pg. 4


EXCEPTION CLASSES :
HIERARCHY OF JAVA EXCEPTION CLASSES

Fig . 3.1
COURSE: OOPJ UNIT: 3 Pg. 5
 All exception types are subclasses of the built-in class Throwable .

 Thus, Throwable is at the top of the exception class hierarchy.

 Immediately below Throwable are two subclasses that


partition exceptions into two distinct branches.
 One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch.
 The other branch is topped by Error, which defines exceptions
that are not expected to be caught under normal circumstances
by your program.

COURSE: OOPJ UNIT: 3 Pg. 6


TYPES OF EXCEPTION
1.Checked Exception
 These exceptions are explicitly handle by JVM with the help of try
and catch block.
 Not handle by the programmer .
 Extended by java.lang.Exception class
 e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.

2.Unchecked Exception
 occur at the time of execution
 Programmer can handle the Exception
 Extended by java.lang.RuntimeException class
 e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException

3.Error
 Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
COURSE: OOPJ UNIT: 3 Pg. 7
UNCAUGHT EXCEPTIONS:
WITHOUT EXCEPTION HANDLING
:public class Testtrycatch1{ WITH EXCEPTION HANDLING

public static void main(String args[ public class Testtrycatch2{


public static void main(String args
]){ []){
int data=50/0;// try{
int data=50/0;
may throw exception }
catch(ArithmeticException e)
System.out.println("rest of the cod {
e..."); System.out.println(e);
}
} System.out.println("rest of the code
...");
} } }
Output: Output:
Exception in thread main
Exception in thread main java.lang.ArithmeticException:/ by
java.lang.ArithmeticException:/ by zero
zero rest of the code...
COURSE: OOPJ UNIT: 3 Pg. 8
INTERNAL WORKING OF JAVA TRY-CATCH BLOCK

Fig . 3.2
COURSE: OOPJ UNIT: 3 Pg. 9
JAVA MULTIPLE CATCH EXCEPTIONS
 In some cases more than on exceptions could be raised by a single
piece of code.
 To handle this type of situation ,use two or more catch clauses.
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}
}
Output:
task1 completed
rest of the code...
COURSE: OOPJ UNIT: 3 Pg. 10
JAVA NESTED TRY BLOCK
 The try block within a try block is known as nested try block in
java.
WHY USE NESTED TRY BLOCK:
 Sometimes a situation may arise where a part of a block may
cause one error and the entire block itself may cause another
error. In such cases, exception handlers have to be nested.
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
COURSE: OOPJ UNIT: 3 Pg. 11
JAVA FINALLY BLOCK
 Java finally block is a block that is used to execute important
code such as closing connection, stream etc.
 Java finally block is always executed whether exception is handled
or not.
 Java finally block follows try or catch block.

Fig . 3.3
COURSE: OOPJ UNIT: 3 Pg. 12
JAVA THROW KEYWORD

 The Java throw keyword is used to explicitly throw an exception.

 We can throw either checked or uncheked exception in java by


throw keyword. The throw keyword is mainly used to throw
custom (user define)exception.
 The syntax of java throw keyword is given below.

throw exception;

Exp: throw new IOException("sorry device error);

COURSE: OOPJ UNIT: 3 Pg. 13


public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:
not valid

COURSE: OOPJ UNIT: 3 Pg. 14


JAVA THROWS KEYWORD

 The Java throws keyword is used to declare an exception.

 If a method is capable of causing an exception that it does not handle, it must


specify this behavior so that callers of the method can guard(protected)
themselves against that exception
 It gives an information to the programmer that there may occur an exception so it
is better for the programmer to provide the exception handling code so that
normal flow can be maintained.
 Exception Handling is mainly used to handle the checked exceptions.

COURSE: OOPJ UNIT: 3 Pg. 15


import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p(); OUT PUT:
System.out.println("normal flow..."); exception handled
} normal flow...
}

COURSE: OOPJ UNIT: 3 Pg. 16


JAVA’S BUILT-IN EXCEPTIONS

 Inside the standard package java.lang, Java defines several exception classes.

COURSE: OOPJ UNIT: 3 Pg. 17


COURSE: OOPJ UNIT: 3 Pg. 18
CREATING YOUR OWN EXCEPTION SUBCLASSES

 Java also support to create new exceptions (user define) by using predefine
exceptions.
 Hear just define a subclass of Exception class

class MyException extends Exception


{
int x;
MyException(int a)
{
x=a;
}
public String toString()
//The toString() method returns the string representation of the object.
//This method is called by println( ) when outputting a Throwable object.
{
return "MyException[" + x + "]:“+”Invalid number”;
} }

COURSE: OOPJ UNIT: 3 Pg. 19


class check
{
public void compute(int y) throws MyException
{
int a=y;
System.out.println("called compute[" + y + "]");
if(a>10)
throw new MyException(y);
System.out.println("normal exit");
}
}

COURSE: OOPJ UNIT: 3 Pg. 20


class myexe
{
public static void main(String args[])
{
check c=new check();
try { OUT PUT:
called compute[ 1]
c.compute(1); Normal exit
called compute[ 20]
c.compute(20); caught:MyException[20]:Invalid number
}
catch(MyException e)
{ System.out.println("caught : " + e); }
}
} COURSE: OOPJ UNIT: 3 Pg. 21
STREAM BASED I/O
 Java I/O (Input and Output) is used to process the input and produce the
output.
 Java uses the concept of stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
 We can perform file handling in java by Java I/O API.
STREAM
 A stream is a sequence of data. In Java a stream is composed of bytes. It's
called a stream because it is like a stream of water that continues to flow.
 In java, 3 streams are created for us automatically. All these streams are
attached with console.
1) System.out: standard output stream (Monitor/file)
2) System.in: standard input stream(keyboard/file)
3) System.err: standard error stream(Monitor/file)
 Let's see the code to print output and error message to the console.
System.out.println("simple message");
System.err.println("error message");
COURSE: OOPJ UNIT: 3 Pg. 22
READING CONSOLE INPUT

 Let's see the code to get input from console.


int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
 In Java, console input is accomplished by reading from System.in.

 To obtain a character based stream that is attached to the console,


wrap System.in in a BufferedReader class.

BufferedReader supports a buffered input stream.


 Java BufferedInputStream class is used to read information from
stream

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

COURSE: OOPJ UNIT: 3 Pg. 23


READING CHARACTERS:

 To read a character from a BufferedReader, use read( ).


 The version of read( ) that we will be using is int read( ) throws IOException

READING STRINGS
 To read a string from the keyboard, use the version of readLine( ) that is a member
of the BufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

COURSE: OOPJ UNIT: 3 Pg. 24


class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in)); Here is a sample
run:
System.out.println("Enter characters, 'q' to quit."); Enter characters, 'q'
to quit.
// read characters 123abcq
do { 1
2
c = (char) br.read(); 3
a
System.out.println(c);
b
} while(c != 'q'); c
q
} }
COURSE: OOPJ UNIT: 3 Pg. 25
Ways to read input from console in Java

 In Java, there are four different ways to read input


from the user in the command line
environment(console).
1. Using Buffered Reader Class
2. Using Scanner Class
3. Using Console Class
4. Using Command line argument

COURSE: OOPJ UNIT: 3 Pg. 26


1. BufferedReader
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
// Reading data using readLine
Input:
String name = reader. readLine(); welcome to Java
// Printing the read line
System.out.println(name); output:
} welcome to Java
}
COURSE: OOPJ UNIT: 3 Pg. 27
2. Scanner Class
// Java program to demonstrate working of Scanner in Java
import java.util.Scanner;
class GetInputFromUser {
public static void main(String args[])
Input :
{
GeeksforGeeks
// Using Scanner for Getting Input from User 12
3.4
Scanner in = new Scanner(System.in);
String s = in.nextLine(); Output ;
System.out.println("You entered string " + s); You entered string
GeeksforGeeks
int a = in.nextInt(); You entered integer 12 You
System.out.println("You entered integer " + a); entered float 3.4
float b = in.nextFloat();
System.out.println("You entered float " + b);
}
} COURSE: OOPJ UNIT: 3 Pg. 28
3. Console Class
// Java program to demonstrate working of System.console()
// Note that this program does not work on IDEs as
// System.console() may require console
public class Sample {
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();
System.out.println("You entered string " + name);
} Input:
} welcome to Java
output:
You entered string welcome
to Java
COURSE: OOPJ UNIT: 3 Pg. 29
4. Using Command line argument
// Program to check for command line arguments
class exp {
public static void main(String[] args)
{
// check if length of args array is greater than 0
if (args.length > 0) {
Compilation: javac exp.java
System.out.println(
Run: java exp Hello World
"The command line arguments are:");
// iterating the args array and printing output:
// the command line arguments
The command line arguments
for (String val : args) are:
System.out.println(val); Hello
} else World
System.out.println("No command line "+"arguments found.");
}
}
COURSE: OOPJ UNIT: 3 Pg. 30
WRITING CONSOLE OUTPUT

 Console output is most easily accomplished with print( ) and println( ), These methods
are defined by the class PrintStream
 Because PrintStream is an output stream derived from OutputStream, it also
implements the low-level method write( ).
 Thus, write( ) can be used to write to the console. The simplest form of write( )
defined by PrintStream is shown here:

void write(int byteval)

DEMONSTRATE SYSTEM.OUT.WRITE().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}} COURSE: OOPJ UNIT: 3 Pg. 31
THE PRINTWRITER CLASS
 PrintWriter is one of the character-based classes. Using a
character-based class for console output makes internationalizing your
program easier.
 PrintWriter defines several constructors. The one we will use is
shown here:
 PrintWriter( OutputStream outputStream, boolean flushingOn)
 PrintWriter supports the print( ) and println( ) methods

OUTPUT:
DEMONSTRATE PRINTWRITER
import java.io.*; This is a string
-7
public class PrintWriterDemo { 4.5E-7
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
COURSE: OOPJ UNIT: 3 Pg. 32
READING AND WRITING FILES
 Java provides a number of classes and methods that allow you to read and write
files
 Two of the most often-used stream classes are FileInputStream and
FileOutputStream, which create byte streams linked to files.
 To open a file, you simply create an object of one of these classes, specifying the
name of the file as an argument to the constructor.

FileInputStream(String fileName) throws FileNotFoundException

FileOutputStream(String fileName) throws FileNotFoundException


 When you are done with a file, you must close it. This is done by calling the
close( )
 To read from a file, you can use a version of read( ) that is defined within
FileInputStream.
 int read( ) throws IOException

COURSE: OOPJ UNIT: 3 Pg. 33


 Each time that it is called, it reads a single byte from the file and
returns the byte as an integer value.
 read( ) returns –1 when the end of the file is encountered.
It can throw an IOException.
 To write a text file in Java, use FileWriter instead of FileReader,
and BufferedOutputWriter instead of BufferedOutputReader.

COURSE: OOPJ UNIT: 3 Pg. 34


/* DISPLAY A TEXT FILE. // At this point, the file is open
To use this program, specify the name and can be read.
of the file that you want to see.
For example, to see a file called TEST.TXT,
// The following reads
use the following command line. characters until EOF is
java ShowFile TEST.TXT encountered.
*/ try {
import java.io.*; do {
class ShowFile { i = fin.read();
public static void main(String args[]) if(i != -1)
{
System.out.print((char) i);
int i;
FileInputStream fin;
} while(i != -1);
// First, confirm that a filename has been } catch(IOException e) {
specified. System.out.println("Error
if(args.length != 1) { Reading File");
System.out.println("Usage: ShowFile }
filename"); // Close the file.
return; try {
}
fin.close();
// Attempt to open the file.
try {
} catch(IOException e) {
fin = new FileInputStream(args[0]); System.out.println("Error
} catch(FileNotFoundException e) { Closing File");
System.out.println("Cannot Open File"); }}} COURSE: OOPJ UNIT: 3 Pg. 35
/* COPY A FILE. // Copy a File.
To use this program, specify the name try {
of the source file and the destination // Attempt to open the files.
file. fin = new FileInputStream(args[0]);
For example, to copy a file called fout = new
FIRST.TXT FileOutputStream(args[1]);
to a file called SECOND.TXT, use the do {
following i = fin.read();
command line. if(i != -1) fout.write(i);
} while(i != -1);
java CopyFile FIRST.TXT SECOND.TXT
} catch(IOException e) {
*/
System.out.println("I/O Error: " + e);
import java.io.*; } finally {
class CopyFile { try {
public static void main(String args[]) if(fin != null) fin.close();
throws IOException } catch(IOException e2) {
{ System.out.println("Error Closing
int i; Input File");
FileInputStream fin = null; }
FileOutputStream fout = null; try {
// First, confirm that both files have if(fout != null) fout.close();
been specified. } catch(IOException e2) {
if(args.length != 2) { System.out.println("Error Closing
System.out.println("Usage: CopyFile Output File");
COURSE: OOPJ UNIT: 3 Pg. 36
WRITING FILE
//Write the File
import java.io.*;
public class Test
{ public static void main(String [] args)
{ // The name of the file to open.
String fileName = "temp.txt";
try { // Assume default encoding.
FileWriter fileWriter = new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character. OUTPUT: (CONTENT OF
bufferedWriter.write("Hello there,"); temp.txt)
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine(); Hello there, here is some
bufferedWriter.write("We are writing"); text.
bufferedWriter.write(" the text to the file.");
We are writing the text to
// Always close files.
the file.
bufferedWriter.close();
} catch(IOException ex)
{ System.out.println( "Error writing to file '" + fileName + "'");
// Or we could just do this: // ex.printStackTrace();
}}}
COURSE: OOPJ UNIT: 3 Pg. 37
Automatically Closing a file
• The close() method of FileOutputStream class is used to close
the file output stream and releases all system resources
associated with this stream.
Ex: FileOutputStream fout= null;
fout.close();
• try-with-resources(automates the process of
releasing a resource, such as a file-After the try
block ends, both fin and fout will have been
closed.)

COURSE: OOPJ UNIT: 3 Pg. 38


ENUMERATIONS
 An enumeration is a “list of named constants”

 Beginning with JDK 5, enumerations were added to the Java


language
 in Java, an enumeration(list) can have constructors, methods, and
instance variables.
 An enumeration is created using the enum keyword, enum in
java is a data type(user define) that contains fixed set of constants.

EXAMPLE
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
OUTPUT:
public static void main(String[] args) { WINTER
SPRING
for (Season s : Season.values())
SUMMER
System.out.println(s); FALL
} }
Note: all enum constants are Public static
COURSE: OOPJ UNIT: 3 Pg. 39
// Use an enum to control a switch
// An enumeration of apple varieties.
enum Apple { statement.
Jonathan, GoldenDel, RedDel, switch(ap) {
Winesap, Cortland case Jonathan:
} System.out.println("Jonathan is
class EnumDemo { red.");
break;
public static void main(String args[])
{ case GoldenDel:
Apple ap; System.out.println("Golden
ap = Apple.RedDel;//static members Delicious is yellow.");
are access through class name break;
// Output an enum value. case RedDel:
System.out.println("Value of ap: " +System.out.println("Red Delicious is
ap); red.");
System.out.println(); break;
ap = Apple.GoldenDel; case Winesap:
// Compare two enum values. System.out.println("Winesap is
if(ap == Apple.GoldenDel) red.");
System.out.println("ap contains
OUTPUT: break;
ValueGoldenDel.\n");
of ap: RedDel case Cortland:
ap contains GoldenDel. System.out.println("Cortland is
red."); COURSE: OOPJ UNIT: 3 Pg. 40
THE VALUES( ) AND VALUEOF( ) METHODS

 All enumerations automatically contain two predefined methods:


values( ) and valueOf( ).
 Their general forms are shown here:

public static enum-type [ ] values( )

public static enum-type valueOf(String str )


 The values( ) method returns an array that contains a list of
the enumeration constants.
 The valueOf( ) method returns the enumeration constant
whose value corresponds to the string passed in str.
 Although you can’t inherit a superclass when declaring an enum,
all enumerations automatically inherit one: java.lang.Enum.

COURSE: OOPJ UNIT: 3 Pg. 41


UNIT OUTCOMES:

Student should be able to

 Learn what exceptions are and how they are handled.


 Learn when to use exception handling and how to create user
defined exceptions
 Learn the difference between various files and streams.

COURSE: OOPJ UNIT: 3 Pg. 42


DIGITAL RESOURCES

 Lecture Notes - Lecture Notes

 Video Lectures - Video Lecture

 E-Book - Java The Complete Reference Ninth Edition

 Model Papers - JNTUA Question Papers

COURSE: OOPJ UNIT: 3 Pg. 43


THANK YOU

COURSE: OOPJ UNIT: 3 Pg. 44

You might also like