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

Core Java - Unit 4

The document discusses exception handling in Java. It provides examples of: 1. Using try/catch blocks to handle exceptions like ArithmeticException. 2. Handling exceptions and continuing program execution using catch blocks. 3. Demonstrating multiple catch blocks to handle different exception types. 4. Issues that can occur if catch block order does not follow subclass ordering. 5. Rethrowing exceptions using throw in catch blocks. 6. Defining methods to throw custom exceptions using throws. 7. Using finally blocks to ensure code is executed whether an exception occurs or not. 8. Creating custom exception subclasses to define application-specific exceptions.

Uploaded by

anji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Core Java - Unit 4

The document discusses exception handling in Java. It provides examples of: 1. Using try/catch blocks to handle exceptions like ArithmeticException. 2. Handling exceptions and continuing program execution using catch blocks. 3. Demonstrating multiple catch blocks to handle different exception types. 4. Issues that can occur if catch block order does not follow subclass ordering. 5. Rethrowing exceptions using throw in catch blocks. 6. Defining methods to throw custom exceptions using throws. 7. Using finally blocks to ensure code is executed whether an exception occurs or not. 8. Creating custom exception subclasses to define application-specific exceptions.

Uploaded by

anji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT-IV - Exception Handling

1) Using try and Catch :

class Exc2 {
public static void main(String args[]) {
int d, a;

try { // monitor a block of code.


d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}

catch (ArithmeticException e) { // catch divide-by-zero error


System.out.println("Division by zero.");
}
Part I
System.out.println("After catch statement.");
}
}

Output:
Division by zero.
After catch statement.

2) // Handle an exception and move on.

import java.util.Random;

class HandleError {
public static void main(String args[]) {
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
3) // Demonstrate multiple catch statements.

class MultipleCatches {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}

Output 1:
C:\>java MultipleCatches
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

CORE JAVA EXAMPLES PGK


Output 2:
C:\>java MultipleCatches TestArg
a=1
Array index oob: java.lang.ArrayIndexOutOfBoundsException:42
After try/catch blocks.

4) /* This program contains an error.


A subclass must come before its superclass in
a series of catch statements. If not,
unreachable code will be created and a
compile-time error will result.
*/
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
}
catch(Exception e) {
System.out.println("Generic Exception catch.");
}

/* This catch is never reached because


ArithmeticException is a subclass of Exception. */

catch(ArithmeticException e) { // ERROR – unreachable


System.out.println("This is never reached.");
}
}
}

5) Throw :
Syntax : throw ThrowableInstance.

// Demonstrate throw.
class ThrowDemo {

static void demoproc() {


try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}

public static void main(String args[]) {


try {
demoproc();
}
catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Output :
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
6) throws Example:

// This is now correct.


class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
CORE JAVA EXAMPLES PGK
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Output:
inside throwOne
caught java.lang.IllegalAccessException: demo

7) finally Example :
// Demonstrate finally.

class FinallyDemo {
// Throw an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.

static void procB() {


try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.

static void procC() {


try {
System.out.println("inside procC");
}
finally {
System.out.println("procC's finally");
}
}

public static void main(String args[]) {


try {
procA();
}
catch (Exception e) {
System.out.println("Exception caught");
}

procB();

procC();

}
}

Output :
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally

8) Creating Your Own Exception Subclasses :


// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
CORE JAVA EXAMPLES PGK
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
}
catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

Output : Called compute(1)


Normal exit
Called compute(20)
Caught MyException[20]

Multy Threading

1) // Creating a thread by extending Thread


class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}

catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

CORE JAVA EXAMPLES PGK


2) // Creating a thread by implementing Runnable interface
class NewThread implements Runnable {
Thread t;
NewThread() {

// Create a new, second thread


t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}

class ThreadDemo {
public static void main(String args[ ] ) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Output : Child thread: Thread[Demo Thread,5,main]


Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

3) // Create multiple threads.

class NewThread implements Runnable {


String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
CORE JAVA EXAMPLES PGK
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

4) Thread Priorities :
final void setPriority(int level)
final int getPriority( )

The value of level must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these values are 1 and 10,
respectively. To return a thread to default priority, specify NORM_PRIORITY, which is currently 5.
5) Write about thread synchronization:
When two or more threads access to a shared( common) resource, they need some way to ensure that the resource will be used
by only one thread at a time. The process by which this is achieved is called synchronization. We can synchronize our code in two ways.
Both involve the use of ―synchronized‖ keyword
a) synchronized methods
b) synchronized code blocks
a) synchronized methods :
We can serialize the access to the methods to only one thread at a time. To do this you simply need to precede the method’s
definition with the keyword synchronized.
synchronized void meth( )
{
Some thread work;
}
When we declare a method synchronized, java creates a ―monitor‖ and hands it over the thread that calls method first time. As
long as the thread holds the monitor, no other thread can enter the synchronized section of code.

b) synchronized code blocks:


We use the keyword synchronized indicating the object you want to restrict access to. The general form is
synchronized (obj)
{
//statements to be synchronized
}

6) Explain Inter – Thread Communication:


Inter thread communication can be defined as the exchange of messages between two or more threads. The transfer of messages
takes place before or after the change of state of thread. Java implements inter- thread communication with help of following methods:

wait():
The method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and
calls notify( ).
Syntax: final void wait( ) throws InterruptedException

notify():
Wakes up the first thread that called wait( ) on the same object. The Object class declaration of this method is:
Syntax: final void notify( )

notifyAll():

CORE JAVA EXAMPLES PGK


Wakes up all the threads that called wait( ) on the same object. the execution of these threads happens as per priority. Highest
priority thread will run first.
Syntax: final void notifyAll( )

Strings

The String Constructors :

1) String s = new String(); //Empty constructor


2) String(char chars[ ]);

Ex : char chars[] = { 'a', 'b', 'c' };


String s = new String(chars);
3) String(char chars[ ], int startIndex, int numChars)

Ex : char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };


String s = new String(chars, 2, 3);
4) String(String strObj)

Ex :

// Construct one String from another.


class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
5) String(byte chrs[ ])
6) String(byte chrs[ ], int startIndex, int numChars

Ex :

// Construct string from subset of char array.


class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}

Output : ABCDEF

CDE

String Operations :

1) String Length
Synt : int length( )
The following fragment prints "3", since there are three characters in the string s:
Ex: char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());

2) String Literals
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
Note : System.out.println("abc".length());

3) String Concatenation :
Ex:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
Output : "He is 9 years old."

CORE JAVA EXAMPLES PGK


Ex: // Using concatenation to prevent long lines.
class ConCat {
public static void main(String args[]) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
}
}

Ex : String s = "four: " + 2 + 2;


System.out.println(s);

Output : four: 22

Ex: String s = "four: " + (2 + 2);


Output : four: 4

Character Extraction :

1) charAt( )

Ex : char ch;
ch = "abc".charAt(1);
2) getChars( )
Syntax : void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Ex :
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
Output :
Demo
3) getBytes( )
Syntax : byte[ ] getBytes( )
4) toCharArray()

Syntax : char[ ] toCharArray( )

String Comparison :

1) equals( ) and equalsIgnoreCase( ) :


Synt : boolean equals(Object str)

boolean equalsIgnoreCase(String str)

Ex : // Demonstrate equals() and equalsIgnoreCase().


class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}

CORE JAVA EXAMPLES PGK


}
Output :
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

2) regionMatches( ) :
Syn : i) boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars)

ii) boolean regionMatches(boolean ignoreCase,int startIndex, String str2,int str2StartIndex, int numChars)

3) startsWith( ) and endsWith( ) :


Syn : boolean startsWith(String str)
boolean endsWith(String str)
Ex : "Foobar".endsWith("bar") --- true
"Foobar".startsWith("Foo")--- true
Syn : startsWith(String str, int startIndex)
Ex : "Foobar".startsWith("bar", 3)
Output : true

4) equals( ) Versus == :
Ex : class EqualsNotEqualTo {
public static void main(String args[]) {
II String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
Output : Hello equals Hello -> true
Hello == Hello -> false

5) compareTo( ) :
Synt : int compareTo(String str)

Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.

Searching Strings :

• indexOf( ) Searches for the first occurrence of a character or substring.


• lastIndexOf( ) Searches for the last occurrence of a character or substring.

Ex :
// Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}

CORE JAVA EXAMPLES PGK


Output :
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
Modifying a String :

1) substring( ) :
Sysntax : String substring(int startIndex);
String substring(int startIndex, int endIndex)
Ex :
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;
do { // replace all matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1) {
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}
Output :
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

2) concat( ) :
Syn: String concat(String str)
Ex : String s1 = "one";
String s2 = s1.concat("two");

3) replace( ) :
Syn: String replace(char original, char replacement)
Ex: String s = "Hello".replace('l', 'w');

4) trim( ) :
Syn: String trim( )
Ex: String s = " Hello World ".trim();

Vector class :
Ex:
// Demonstrate various Vector operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector<Integer> v = new Vector<Integer>(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.addElement(4);
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(5);
CORE JAVA EXAMPLES PGK
System.out.println("Current capacity: " +
v.capacity());
v.addElement(6);
v.addElement(7);
System.out.println("Current capacity: " +
v.capacity());
v.addElement(9);
v.addElement(10);
System.out.println("Current capacity: " +
v.capacity());
v.addElement(11);
v.addElement(12);
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3.");
// Enumerate the elements in the vector.
Enumeration<Integer> vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Output:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5 6 7 9 10 11 12

CORE JAVA EXAMPLES PGK

You might also like