0% found this document useful (0 votes)
2 views39 pages

Java Unit 4 Complete

The document provides an overview of exception handling in Java, detailing types of exceptions, their differences, and the use of try-catch blocks. It also covers the Java File class, character and byte streams, and the Scanner class for input handling. Key concepts include checked and unchecked exceptions, custom exceptions, and the importance of maintaining normal application flow.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views39 pages

Java Unit 4 Complete

The document provides an overview of exception handling in Java, detailing types of exceptions, their differences, and the use of try-catch blocks. It also covers the Java File class, character and byte streams, and the Scanner class for input handling. Key concepts include checked and unchecked exceptions, custom exceptions, and the importance of maintaining normal application flow.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

www.Jntufastupdates.

com 1
www.Jntufastupdates.com 2
www.Jntufastupdates.com 3
www.Jntufastupdates.com 4
www.Jntufastupdates.com 5
www.Jntufastupdates.com 6
www.Jntufastupdates.com 7
www.Jntufastupdates.com 8
www.Jntufastupdates.com 9
www.Jntufastupdates.com 10
www.Jntufastupdates.com 11
www.Jntufastupdates.com 12
www.Jntufastupdates.com 13
www.Jntufastupdates.com 14
www.Jntufastupdates.com 15
www.Jntufastupdates.com 16
www.Jntufastupdates.com 17
www.Jntufastupdates.com 18
www.Jntufastupdates.com 19
www.Jntufastupdates.com 20
www.Jntufastupdates.com 21
www.Jntufastupdates.com 22
www.Jntufastupdates.com 23
www.Jntufastupdates.com 24
www.Jntufastupdates.com 25
Exception Handling
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

In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.

Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun microsystem says there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between checked and unchecked exceptions

1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.

2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptionsarenotchecked at compile-timeratherthey arechecked at runtime.

3) Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionErroretc.

JAVA PROGRAMMING Page 48


Hierarchy of Java Exception classes

Checked and UnChecked Exceptions

JAVA PROGRAMMING Page 49


Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within
the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch

1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}

Syntax of try-finally block

1. try{
2. //code that may throw exception
3. }finally{}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.

You can use multiple catch block with a single try.

Problem without exception handling

Let's try to understand the problem if we don't use try-catch block.

public class Testtrycatch1{


public static void main(String args[]){
int data=50/0;//may throw exception
System.out.println("rest of the code...");
}}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero

As displayed in the above example, rest of the code is not executed (in such case, rest of the
code... statement is not printed).

There can be 100 lines of code after exception. So all the code after exception will not be
executed.

Solution by exception handling

Let's see the solution of above problem by java try-catch block.

public class Testtrycatch2{

JAVA PROGRAMMING Page 50


public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){System.out.println(e);}
System.out.println("rest of the code...");
}}
1. Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.

Java Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java multi
catch block.

Let's see a simple example of java multi-catch block.

1. public class TestMultipleCatchBlock{


2. public static void main(String args[]){
3. try{
4. int a[]=new int[5];
5. a[5]=30/0;
6. }
7. catch(ArithmeticException e){System.out.println("task1 is completed");}
8. catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");
9. }
10. catch(Exception e){System.out.println("common task completed");
11. }
12. System.out.println("rest of the code...");
13. } }

Output:task1 completed
rest of the code...

Java nested try example

Let's see a simple example of java nested try block.

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);}

JAVA PROGRAMMING Page 51


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..");
}
1. }
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.

Usage of Java finally

Case 1

Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...

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 exception. We will see custom exceptions later.

JAVA PROGRAMMING Page 52


The syntax of java throw keyword is given below.

1. throw exception;

Java throw keyword example

In this example, we have created the validate method that takes integer value as a parameter. If
the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.

1. 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


Java throws keyword

The Java throws keyword is used to declare an 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. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.

Syntax of java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }
4.
Java throws example

Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.

import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception

JAVA PROGRAMMING Page 53


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();
System.out.println("normal flow..."); } }
Output:
exception handled
normal flow...

Java Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.

By the help of custom exception, you can have your own exception and message.

Let's see a simple example of java custom exception.

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...");


}}

Output:Exception occured: InvalidAgeException:not valid rest of the code...

JAVA PROGRAMMING Page 54


Java offers two types of streams:
1. character streams
2. byte streams.

These streams can be different in how they are handling data and the type of data they are handling.

1. Character Streams:
Character streams are designed to address character based records, which includes textual records
inclusive of letters, digits, symbols, and other characters. These streams are represented by way of
training that quit with the phrase "Reader" or "Writer" of their names, inclusive of FileReader,
BufferedReader, FileWriter, and BufferedWriter.

Character streams offer a convenient manner to read and write textual content-primarily based
information due to the fact they mechanically manage character encoding and decoding. They
convert the individual statistics to and from the underlying byte circulation the usage of a particular
individual encoding, such as UTF-eight or ASCII.It makes person streams suitable for operating with
textual content files, analyzing and writing strings, and processing human-readable statistics.

2. Byte Streams:
Byte streams are designed to deal with raw binary data, which includes all kinds of data,
including characters, pictues, audio, and video. These streams are represented through
cclasses that cease with the word "InputStream" or "OutputStream" of their names,along
with FileInputStream,BufferedInputStream, FileOutputStream and BufferedOutputStream.

Byte streams offer a low-stage interface for studying and writing character bytes or blocks of
bytes. They are normally used for coping with non-textual statistics, studying and writing
files of their binary form, and running with network sockets. Byte streams don't perform any
individual encoding or deciphering. They treat the data as a sequence of bytes and don't
interpret it as characters.
Here are the some of the differences listed:

Example code for Character Stream:


FileName: CharacterStreamExample.java

1. import java.io.CharArrayReader;
2. import java.io.IOException;
3.
4. public class CharacterStreamExample
5. {
6. public static void main(String[] args) {
7. // Creates an array of characters
8. char[] array = {'H','e','l','l','o'};
9. try {
10. CharArrayReader reader=new CharArrayReader(array);
11. System.out.print("The characters read from the reader:");
12. int charRead;
13. while ((charRead=reader.read())!=-1) {
14. System.out.print((char)charRead+",");
15. }
16. reader.close();
17. } catch (IOException ex)
18. {
19. ex.printStackTrace();
20. }
21. }
22. }
23. Output: The characters read from the reader:H,e,l,l,o,

Example code for Byte Stream:


FileName: ByteStreamExample.java

1. import java.io.ByteArrayInputStream;
2.
3. public class ByteStreamExample
4. {
5. public static void main(String[] args)
6. {
7. // Creates the array of bytes
8. byte[] array = {10,20,30,40};
9. try {
10. ByteArrayInputStream input=new ByteArrayInputStream(array);
11. System.out.println("The bytes read from the input stream:");
12. for (int i=0;i<array.length;i++)
13. {
14. // Reads the bytes
15. int data=input.read();
16. System.out.print(data+",");
17. }
18. input.close();
19. } catch (Exception ex)
20. {
21. ex.getStackTrace();
22. }
23. }
24. }

25. The bytes read from the input stream:10,20,30,40.


Java File Class
The File class is an abstract representation of file and directory pathname. A pathname can
be either absolute or relative.

The File class have several methods for working with directories and files such as creating
new directories or files, deleting and renaming directories or files, listing the contents of a
directory etc.

Fields

Constructors
Java File Example 1
1. import java.io.*;
2. public class FileDemo {
3. public static void main(String[] args) {
4.
5. try {
6. File file = new File("javaFile123.txt");
7. if (file.createNewFile()) {
8. System.out.println("New File is created!");
9. } else {
10. System.out.println("File already exists.");
11. }
12. } catch (IOException e) {
13. e.printStackTrace();
14. }
15.
16. }
17. }
Output: New File is created!
Java File Example 2
1. import java.io.*;
2. public class FileDemo2 {
3. public static void main(String[] args) {
4.
5. String path = "";
6. boolean bool = false;
7. try {
8. // createing new files
9. File file = new File("testFile1.txt");
10. file.createNewFile();
11. System.out.println(file);
12. // createing new canonical from file object
13. File file2 = file.getCanonicalFile();
14. // returns true if the file exists
15. System.out.println(file2);
16. bool = file2.exists();
17. // returns absolute pathname
18. path = file2.getAbsolutePath();
19. System.out.println(bool);
20. // if file exists
21. if (bool) {
22. // prints
23. System.out.print(path + " Exists? " + bool);

24. }
25. } catch (Exception e) {
26. // if any error occurs
27. e.printStackTrace();
28. }
29. }
30. }
31. Output:

32. testFile1.txt
33. /home/Work/Project/File/testFile1.txt
34. true
35. /home/Work/Project/File/testFile1.txt Exists? true
Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read
input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace
by default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a
regular expression. It is the simplest way to get input in Java. By the help of Scanner in
Java, we can get input from the user in primitive types such as int, long, double, byte,
float, short, etc.

The Java Scanner class provides nextXXX() methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0)
method which returns a single character.

Java Scanner Class Declaration


1. public final class Scanner
2. extends Object
3. implements Iterator<String>
How to get Java Scanner
To get the instance of Java Scanner which reads input from the user, we need to pass the
input stream (System.in) in the constructor of Scanner class. For Example:
1. Scanner in = new Scanner(System.in);

Example 1 : Java Scanner where we are getting a single input from the user. Here, we
are asking for a string through in.nextLine() method.

1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);
8. in.close();
9. }
10. }

11. Enter your name: sonoo jaiswal


12. Name is: sonoo jaiswal

You might also like