SlideShare ist ein Scribd-Unternehmen logo
1 von 4
Downloaden Sie, um offline zu lesen
1
Chapter 5 Lab Manual
Program 35
//The program shown below terminates abnormally
if you enter a floating-point value instead of an
integer.
package ch5;
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
System.out.println("Enter a number :");
int num= reader.nextInt();
System.out.println("The number is :" +
num);
} }
Program 36
package ch4;
import java.util.Scanner;
import java.util.*;
public class ExceptionDemo {
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
System.out.println("Enter a number :");
try {
int num= reader.nextInt();
System.out.println("The number is :" +
num);
}
catch (InputMismatchException e){
System.out.println("There is type mis
match :");
}
finally{
System.out.println("This part is always
done");
}} }
Program 37
package ch5;
class Example{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be
divided by zero");
}
/* Finally block will always execute even if there
is no exception in try block*/
finally{
System.out.println("This is finally
block");
}
System.out.println("Out of try-catch-finally");
}
}
Program 38
//multiple catch blocks
package ch5;
public class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can
throw exception so we handled it by placing these
statements inside try and handled the exception in
catch block */
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try
block");
}
catch (ArithmeticException e) {
/* This block will only execute if any
Arithmetic exception occurs in try block */
System.out.println("You should not divide a
number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which
means it can handle all the exceptions. This will
execute if the exception is not handled by previous
catch blocks.*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in
Java.");
}}
Program 39
// Multiple catch blocks that select the exact
exception
package ch5;
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try
block");
}
catch(ArithmeticException e){
System.out.println("Warning:
ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning:
ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other
exception");
}
System.out.println("Out of try-catch block...");
}}
2
Program 40
// The use of throw
package ch5;
public class Examplezero{
void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not
Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
Examplezero obj = new Examplezero();
obj.checkAge(15);
System.out.println("End Of Program");
}
}
Program 41
// The use of throws for multiple exception selection
package ch5;
import java.io.*;
class ThrowExample {
void myMethod(int num)throws IOException,
ClassNotFoundException{
if(num==1)
thrownew IOException("IOException
Occurred");
else
thrownew
ClassNotFoundException("ClassNotFoundExcepti
on");
} }
class Examples{
public static void main(String args[]){
try{
ThrowExample obj=newThrowExample();
obj.myMethod(1);
}catch(Exception ex){
System.out.println(ex);
} }}
Program 42
package ch5;
public class throwsdividedbyzero{
int division(int a, int b) throws
ArithmeticException{
int t = a/b;
return t;}
public static void main(String args[]){
throwsdividedbyzero obj = new
throwsdividedbyzero();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide
number by zero");
} } }
3
Chapter 6 Lab Manual
Program 43
package ch6;
// Use a BufferedReader to read characters from the
console.
import java.io.*;
class BRRead {
public static void main(String args[])
throws IOException{
char c;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char)br.read();
System.out.println(c);
} while(c != 'q');
}}
Program 44
package ch6;
// Read a string from console using a
BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
}
while(!str.equals("stop"));
} }
Program 45
package ch6;
//copy byte
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws
IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}} }}
Program 46
package ch6;
// Creating a text File using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile {
public static void main(String[] args) throws
IOException {
// Accept a string
String str = "File Handling in Java using "+
" FileWriter and FileReader";
// attach a file to FileWriter
FileWriter fw=new FileWriter("output.txt");
// read character wise from string and write
// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));
System.out.println("Writing successful");
//close the file
fw.close();
} }
Program 47
package ch6;
// copy characters
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws
IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new
FileReader("xanadu.txt");
outputStream = new
FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}}}}
Program 48
package ch6;
// read file from the disk
4
import java.io.*;
public class FileStats{
public static void main(String[] args) throws
IOException {
// the file must be called 'temp.txt'
String s = "temp.txt";
// see if file exists
File f = new File(s);
if (!f.exists()){
System.out.println("'" + s + "' does not exit. Bye!");
return;
}
BufferedReader inputFile = new
BufferedReader(new FileReader(s));
// read lines from the disk file, compute stats
String line;
int nLines = 0;
int nCharacters = 0;
while ((line = inputFile.readLine()) != null){
nLines++;
nCharacters += line.length();
}
// output file statistics
System.out.println("File statistics for '” + s +
“'...");
System.out.println("Number of lines = " + nLines);
System.out.println("Number of characters = " +
nCharacters);
// close disk file
inputFile.close();
} }
Program 49
// writ file on the disk
package ch6;
import java.io.*;
class FileWrite {
public static void main(String[] args) throws
IOException {
// open keyboard for input (call it 'stdin')
BufferedReader stdin =new BufferedReader(new
InputStreamReader(System.in));
// Let's call the output file 'junk.txt'
String s = "junk.txt";
// check if output file exists
File f = new File(s);
if (f.exists())
{
System.out.print("Overwrite " + s + " (y/n)? ");
if(!stdin.readLine().toLowerCase().equals("y"))
return;
}
//open file for output
PrintWriter outFile =
new PrintWriter(new BufferedWriter(new
FileWriter(s)));
// inform the user what to do
System.out.println("Enter some text on the
keyboard...");
System.out.println("(^z to terminate)");
// read from keyboard, write to file output stream
String s2;
while ((s2 = stdin.readLine()) != null)
outFile.println(s2);
// close disk file
outFile.close();
} }
Program 50
package ch6;
//Java program to practice using String Buffer class
and its methods.
import java.lang.String;
class stringbufferdemo {
public static void main(String arg[]) {
StringBuffer sb=new StringBuffer("This is my
college");
System.out.println("This string sb is : " +sb);
System.out.println("The length of the string sb is : "
+sb.length());
System.out.println("The capacity of the string sb is :
" +sb.capacity());
System.out.println("The character at an index of 6 is
: " +sb.charAt(6));
sb.setCharAt(3,'x');
System.out.println("After setting char x at position
3 : " +sb);
System.out.println("After appending : "
+sb.append(" in gulbarga "));
System.out.println("After inserting : "
+sb.insert(19,"gpt "));
System.out.println("After deleting : "
+sb.delete(19,22));
} }
Program 51
package ch6;
// Java Program to illustrate reading from FileReader
// using BufferedReader
import java.io.*;
public class ReadFromFile2
{
public static void main(String[] args)throws
Exception
{
// We need to provide file path as the parameter:
// double backquote is to avoid compiler interpret
words
// like test as t (ie. as a escape sequence)
File file = new File("C:UsersDesktoptest.txt");
//use your own paths
BufferedReader br = new BufferedReader(new
FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With SpockIT Weekend
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujeigersonjack
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладкаDEVTYPE
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageESUG
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 

Was ist angesagt? (15)

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Smarter Testing With Spock
Smarter Testing With SpockSmarter Testing With Spock
Smarter Testing With Spock
 
Spock framework
Spock frameworkSpock framework
Spock framework
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
 
Java practical
Java practicalJava practical
Java practical
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 

Ähnlich wie Lab Manual Programs Handle Exceptions, File I/O

Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
The Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdfThe Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdfanjanacottonmills
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in JavaManuela Grindei
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfshahidqamar17
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системеDEVTYPE
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into itmelakusisay507
 
Write a java program that allows the user to input the name of a fil.docx
 Write a java program that allows the user to input  the name of a fil.docx Write a java program that allows the user to input  the name of a fil.docx
Write a java program that allows the user to input the name of a fil.docxajoy21
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docxnoreendchesterton753
 
2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdfrbjain2007
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfmanojmozy
 

Ähnlich wie Lab Manual Programs Handle Exceptions, File I/O (20)

Inheritance
InheritanceInheritance
Inheritance
 
Bhaloo
BhalooBhaloo
Bhaloo
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
CORE JAVA-1
CORE JAVA-1CORE JAVA-1
CORE JAVA-1
 
Java programs
Java programsJava programs
Java programs
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
The Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdfThe Java Program for the above given isimport java.io.File;impo.pdf
The Java Program for the above given isimport java.io.File;impo.pdf
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Exceptions and errors in Java
Exceptions and errors in JavaExceptions and errors in Java
Exceptions and errors in Java
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
 
Java 104
Java 104Java 104
Java 104
 
ExtraFileIO.pptx
ExtraFileIO.pptxExtraFileIO.pptx
ExtraFileIO.pptx
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into it
 
Write a java program that allows the user to input the name of a fil.docx
 Write a java program that allows the user to input  the name of a fil.docx Write a java program that allows the user to input  the name of a fil.docx
Write a java program that allows the user to input the name of a fil.docx
 
Write a java program that allows the user to input the name of a file.docx
Write a java program that allows the user to input  the name of a file.docxWrite a java program that allows the user to input  the name of a file.docx
Write a java program that allows the user to input the name of a file.docx
 
2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf2. Write a program which will open an input file and write to an out.pdf
2. Write a program which will open an input file and write to an out.pdf
 
import java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdfimport java.io.BufferedReader;import java.io.File;import java.io.pdf
import java.io.BufferedReader;import java.io.File;import java.io.pdf
 

Mehr von siragezeynu

Mehr von siragezeynu (12)

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
6 database
6 database 6 database
6 database
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
 

Kürzlich hochgeladen

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Kürzlich hochgeladen (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Lab Manual Programs Handle Exceptions, File I/O

  • 1. 1 Chapter 5 Lab Manual Program 35 //The program shown below terminates abnormally if you enter a floating-point value instead of an integer. package ch5; import java.util.Scanner; public class ExceptionDemo { public static void main(String args[]){ Scanner reader=new Scanner(System.in); System.out.println("Enter a number :"); int num= reader.nextInt(); System.out.println("The number is :" + num); } } Program 36 package ch4; import java.util.Scanner; import java.util.*; public class ExceptionDemo { public static void main(String args[]){ Scanner reader=new Scanner(System.in); System.out.println("Enter a number :"); try { int num= reader.nextInt(); System.out.println("The number is :" + num); } catch (InputMismatchException e){ System.out.println("There is type mis match :"); } finally{ System.out.println("This part is always done"); }} } Program 37 package ch5; class Example{ public static void main(String args[]) { try{ int num=121/0; System.out.println(num); } catch(ArithmeticException e){ System.out.println("Number should not be divided by zero"); } /* Finally block will always execute even if there is no exception in try block*/ finally{ System.out.println("This is finally block"); } System.out.println("Out of try-catch-finally"); } } Program 38 //multiple catch blocks package ch5; public class Example1 { public static void main(String args[]) { int num1, num2; try { /* We suspect that this block of statement can throw exception so we handled it by placing these statements inside try and handled the exception in catch block */ num1 = 0; num2 = 62 / num1; System.out.println(num2); System.out.println("Hey I'm at the end of try block"); } catch (ArithmeticException e) { /* This block will only execute if any Arithmetic exception occurs in try block */ System.out.println("You should not divide a number by zero"); } catch (Exception e) { /* This is a generic Exception handler which means it can handle all the exceptions. This will execute if the exception is not handled by previous catch blocks.*/ System.out.println("Exception occurred"); } System.out.println("I'm out of try-catch block in Java."); }} Program 39 // Multiple catch blocks that select the exact exception package ch5; class Example2{ public static void main(String args[]){ try{ int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e){ System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Warning: ArrayIndexOutOfBoundsException"); } catch(Exception e){ System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); }}
  • 2. 2 Program 40 // The use of throw package ch5; public class Examplezero{ void checkAge(int age){ if(age<18) throw new ArithmeticException("Not Eligible for voting"); else System.out.println("Eligible for voting"); } public static void main(String args[]){ Examplezero obj = new Examplezero(); obj.checkAge(15); System.out.println("End Of Program"); } } Program 41 // The use of throws for multiple exception selection package ch5; import java.io.*; class ThrowExample { void myMethod(int num)throws IOException, ClassNotFoundException{ if(num==1) thrownew IOException("IOException Occurred"); else thrownew ClassNotFoundException("ClassNotFoundExcepti on"); } } class Examples{ public static void main(String args[]){ try{ ThrowExample obj=newThrowExample(); obj.myMethod(1); }catch(Exception ex){ System.out.println(ex); } }} Program 42 package ch5; public class throwsdividedbyzero{ int division(int a, int b) throws ArithmeticException{ int t = a/b; return t;} public static void main(String args[]){ throwsdividedbyzero obj = new throwsdividedbyzero(); try{ System.out.println(obj.division(15,0)); } catch(ArithmeticException e){ System.out.println("You shouldn't divide number by zero"); } } }
  • 3. 3 Chapter 6 Lab Manual Program 43 package ch6; // Use a BufferedReader to read characters from the console. import java.io.*; class BRRead { public static void main(String args[]) throws IOException{ char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char)br.read(); System.out.println(c); } while(c != 'q'); }} Program 44 package ch6; // Read a string from console using a BufferedReader. import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } } Program 45 package ch6; //copy byte import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); }} }} Program 46 package ch6; // Creating a text File using FileWriter import java.io.FileWriter; import java.io.IOException; class CreateFile { public static void main(String[] args) throws IOException { // Accept a string String str = "File Handling in Java using "+ " FileWriter and FileReader"; // attach a file to FileWriter FileWriter fw=new FileWriter("output.txt"); // read character wise from string and write // into FileWriter for (int i = 0; i < str.length(); i++) fw.write(str.charAt(i)); System.out.println("Writing successful"); //close the file fw.close(); } } Program 47 package ch6; // copy characters import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); }}}} Program 48 package ch6; // read file from the disk
  • 4. 4 import java.io.*; public class FileStats{ public static void main(String[] args) throws IOException { // the file must be called 'temp.txt' String s = "temp.txt"; // see if file exists File f = new File(s); if (!f.exists()){ System.out.println("'" + s + "' does not exit. Bye!"); return; } BufferedReader inputFile = new BufferedReader(new FileReader(s)); // read lines from the disk file, compute stats String line; int nLines = 0; int nCharacters = 0; while ((line = inputFile.readLine()) != null){ nLines++; nCharacters += line.length(); } // output file statistics System.out.println("File statistics for '” + s + “'..."); System.out.println("Number of lines = " + nLines); System.out.println("Number of characters = " + nCharacters); // close disk file inputFile.close(); } } Program 49 // writ file on the disk package ch6; import java.io.*; class FileWrite { public static void main(String[] args) throws IOException { // open keyboard for input (call it 'stdin') BufferedReader stdin =new BufferedReader(new InputStreamReader(System.in)); // Let's call the output file 'junk.txt' String s = "junk.txt"; // check if output file exists File f = new File(s); if (f.exists()) { System.out.print("Overwrite " + s + " (y/n)? "); if(!stdin.readLine().toLowerCase().equals("y")) return; } //open file for output PrintWriter outFile = new PrintWriter(new BufferedWriter(new FileWriter(s))); // inform the user what to do System.out.println("Enter some text on the keyboard..."); System.out.println("(^z to terminate)"); // read from keyboard, write to file output stream String s2; while ((s2 = stdin.readLine()) != null) outFile.println(s2); // close disk file outFile.close(); } } Program 50 package ch6; //Java program to practice using String Buffer class and its methods. import java.lang.String; class stringbufferdemo { public static void main(String arg[]) { StringBuffer sb=new StringBuffer("This is my college"); System.out.println("This string sb is : " +sb); System.out.println("The length of the string sb is : " +sb.length()); System.out.println("The capacity of the string sb is : " +sb.capacity()); System.out.println("The character at an index of 6 is : " +sb.charAt(6)); sb.setCharAt(3,'x'); System.out.println("After setting char x at position 3 : " +sb); System.out.println("After appending : " +sb.append(" in gulbarga ")); System.out.println("After inserting : " +sb.insert(19,"gpt ")); System.out.println("After deleting : " +sb.delete(19,22)); } } Program 51 package ch6; // Java Program to illustrate reading from FileReader // using BufferedReader import java.io.*; public class ReadFromFile2 { public static void main(String[] args)throws Exception { // We need to provide file path as the parameter: // double backquote is to avoid compiler interpret words // like test as t (ie. as a escape sequence) File file = new File("C:UsersDesktoptest.txt"); //use your own paths BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null) System.out.println(st); } }