Java UnitII Ppt
Java UnitII Ppt
Checked Exception
Unchecked Exception
Error
Checked Exceptions
Inherit from class Exception but not from
RuntimeException.
Checked Exception:
➢ These Exceptions are explicitly handled in the code itself with
the help of
try-catch blocks.
➢ Checked Exceptions are extended from the
import java.lang.Exception;
UnChecked Exception:
➢ These Exception are not essentially handled in the program
code; instead
the JVM handles such exceptions.
➢ Unchecked Exceptions are extended from the
Import java.lang.RuntimeException;
Exception Handling Mechanism
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Example
public class JavaExceptionExample{
try{
int a=Interger.parseInt(args[0]);
int b=Interger.parseInt(args[1]);
int data=a/b;
catch(ArithmeticException e)
System.out.println(e);
}
catch multiple exceptions
A try block can be followed by one or more catch blocks.
So, if you have to perform different tasks at the occurrence of different exceptions, use java
multi-catch block.
try{
a[5]=30/0;
catch(ArithmeticException e)
catch(ArrayIndexOutOfBoundsException e)
catch(Exception e)
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or unchecked exception in java by throw
keyword.
The throw keyword is mainly used to throw custom exception.
Syntax: throw new Throwable subclass;
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..."); } }
import java.io.*;
class ThrowExample {
if(num==1)
else
try{
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex); } } }
User-defined Exceptions
We can create your own exceptions in Java. Keep the
following points in mind when writing your own
exception classes.
All exceptions must be a child of Throwable.
If you want to write a checked exception that is
automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
If you want to write a runtime exception, you need to
extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{ }
Example of User Defined Exception
class MyException extends Exception
{
public MyException(String s)
{ // Call constructor of parent Exception
super(s); } }
public class Main
{ // Driver Program
public static void main(String args[])
{ try {
// Throw an object of user defined exception
throw new MyException("GeeksGeeks"); }
catch (MyException ex) {
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage()); } } }
Input /Output Basics
Byte Streams
Character Streams
File Handling in Java
Reading and Writing File in Java
File Handling in Java
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
There are two types of java streams (based on the data
types)
Byte Stream
Character Stream
Byte Stream
Byte streams are used to perform input and output of 8-
bit bytes. When we want to read/write binary data, we
can use byte streams.
• Create a File
• Read from a File
• Write to a File
• Delete a File
Create a File
No buffering. Each write goes straight to Uses an internal buffer (default 8 KB) to
Buffering
the file. reduce file I/O operations.
During the life time of a thread, there are many states it can enter.
•They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Thread Methods
There are two ways to create
a thread:
1. By extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
2. By implementing Runnable
interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
Output:
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:1
running thread priority is:10
Synchronization
Synchronization in java is the capability to control the access of
multiple threads to any shared resource.
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{ Thread.sleep(400);
}catch(Exception e){System.out.println(e);} } } }
Table t;
MyThread1(Table t){
this.t=t; }
t.printTable(5); } }
Table t;
MyThread2(Table t){
this.t=t; }
t.printTable(100); } }
t1.start();
t2.start(); } }
Inter thread communication
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
1) wait() method: Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.
Method Description:
2. public final void wait(long timeout)throws InterruptedException (waits for the specified amount
of time.)
2) notify() method: Wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
Syntax:
3) notifyAll() method: Wakes up all threads that are waiting on this object's monitor. Syntax: