|
Exception (eccezione)
Start up Eclipse > Select “myPackage” > new > class > name > ArrayOutRange> Finish.
package mioPackage;
public class ArrayfuoriCampo {
public static void main(String[] args) {
try { // qui può avvenire una eccezione
int n = 0;
String colore[ ]={"Rosso", "Giallo", "Verde"};
while(n < 4){ // accade una eccezione se l'indice di string è uguale a 3
System.out.println(colore[n]);
n++;
}}catch(ArrayEccezioneIndexOltreLimite e){
// elabora l'eccezione
System.out.println(“ ”);
System.out.println("Exception Occurs!");
System.out.println("L'indice dell'Array è fuori limite!");
}}}
package |mioPackage|;
public class |ArrayfuoriCampo|{
public static void main(String[] args) {
try { // qui può avvenire una eccezione
int |n| =|0|;
String |colore|[ ]={"|Rosso|", "|Giallo|", "|Verde|"};
while(|n|<|4|){ // accade l'eccezione se l'indice di string è uguale a 3
System.out.println(|colore|[|n|]);
|n|++;
}}catch(|ArrayEccezioneIndexOltreLimite e|){
// elabora l'eccezione
System.out.println(“ ”);
System.out.println("|Accade una eccezione!|");
System.out.println("|L'indice dell'Array è fuori limite!|");
}}}
Fate clic sul pulsante verde col triangolo bianco nella barra degli strumenti per eseguire il programma e vedere l'output:
Catch Exception 1 (Acchiappa l'eccezione 1)
try { // prova se qui può avvenire una eccezione
catch ( Exception ) {......} //elabora l'eccezione
“try-catch” può catturare l'eccezione e gestirla
Esempio
public class ExceptionSample {
public static void main (String args [ ]) {
try { // qualche codice che può provocare una eccezione
int a=10, b=0, c;
c = a/b; //errore! perché “b” è 0.
System.out.print ( c );
}
catch ( ArithmeticException e) { // handle the exception
System.out.print (" Divisione per zero ");
}}}(
SINTASSI
public class |ExceptionSample|{
public static void main (String args [ ]) {
try { // qualche codice che può provocare una eccezione
int |a|=|10|, |b|=|0|, |c|;
|a|= |a|/|b|; //errore! perché “b” è = 0.
System.out.print ( |c| );
}
catch ( |ArithmeticException e|) { // GESTISCE L'ECCEZIONE
System.out.print ("|Divisione per zero| ");
}}}
Output: Divisione per zero
try { // prova se qui può avvenire una eccezione
(Acchiappa l'eccezione 2) Catch Exception (2)
Esempio
public class ExceptionSample {
public static void main (String args [ ]) {
try {
int a[ ] = new int [10]; // the last index is 9
a[10]=100; // error! because the index is out bound.
System.out.print ( a[10] );
}
catch ( ArrayIndexOutOfBoundsException e) {
System.out.print (" Array index out of bounds ");
}}}( Output: Array index out of bounds )
SINTASSI
public class |ExceptionSample|{
public static void main (String args [ ]) {
try {
int |a|[ ] = new int [|10|]; // ultimo indice =9
|a|[|10|]=|100|; // error! indice = 10 >9.
System.out.print (|a|[|10|]);
}
catch ( |ArrayIndexOutOfBoundsException e|) {
System.out.print ("|Indice dell'Array fuori limite|");
}}}
Output: Indice dell'Array fuori limite
Spiegazione:
“try{…}” ha “a[10]”, e causa eccezione.
“catch {…}” elabora l'eccezione
(Acchiappa l'eccezione 3) Catch Exception (3)
try { // prova se qui può avvenire una eccezione
catch ( Exception ) {......} //elabora l'eccezione
“try-catch” può catturare l'eccezione e gestirla
"Try {...}" ch contiene "ABC".charAt(100); e provoca un'eccezione, perché la lunghezza di "ABC" è 3, e non ha il centesimo carattere.Esempio
public class ExceptionSample {
public static void main (String args [ ]) {
try {
char ch = "ABC".charAt(100); //errore indice fuori limite
System.out.print ( ch );
}
catch (IndexOutOfBoundsException e) {
System.out.print ( "Indice di Ch oltre il limite" );
}}}
SINTASSI
public class |ExceptionSample|{
public static void main (String args [ ]) {
try {
char |ch| = "|ABC|".charAt(|100|); //errore indice fuori limite
System.out.print ( |ch| );
}
catch (|IndexOutOfBoundsException e|) {
System.out.print ( "|Indice di Ch oltre il limite|" );
}}}
Output: Indice di Ch oltre il limite.
Spiegazione:<(h3>
Comando Finally
Il blocco try-catch può essere seguito da un comando "Finally" che deve essere sempre eseguito alla fine.
Try { ....} // alcuni codici che potrebbero presentare eccezioni
Catch (eccezione) {...... } // eccezione del processo
Finally {....} // sempre eseguito alla fine
Esempio
public class ExceptionSample {
public static void main (String args [ ]) {
try {char ch = "ABC".charAt(100);} // errore!
catch (IndexOutOfBoundsException e) {
System.out.print ( "Character index out of bounds.");}
finally { System.out.print("The End"); } // DA ESEGUIRE ALLA FINE
SINTASSI
public class |ExceptionSample| {
public static void main (String args [ ]) {
try {char |ch| = "|ABC|".charAt(|100|);} // errore!
catch (|IndexOutOfBoundsException e|) {
System.out.print ( "|Indice dei caratteri fuori limite.|");}
finally { System.out.print("|Finito!|"); } // DA ESEGUIRE ALLA FINE
}}Output 1: Character index out of bounds
Output 2: FinitoSpiegazione:
“finally {System.out.print(“Finito!”);}” è eseguito alla fine
Throw Exception
Esempio
public class ExceptionSample {
public static void main (String args [ ]) {
try {
int a[ ] = new int[10]; // L'ultimo elemento è [9], without a[10].
if ( a[10] >0 )
throw new ArrayIndexOutOfBoundsException("Error"); // throw
}
catch ( ArrayIndexOutOfBoundsException e) {
System.out.print ("Error index:"+e.getMessage( )); // alert
}}}SINTASSI
public class |ExceptionSample| {
public static void main (String args [ ]) {
try {
int|a|[ ]=new int[|10|];//L'ultimo elemento è [9] without a[10].
if ( |a||10|[ ] >0 )
throw new |ArrayIndexOutOfBoundsException|("Errore"); // throw
}
catch (|ArrayIndexOutOfBoundsException|) {
System.out.print ("Indice dell'errore:"+e.getMessage( )); // alert
}}}
Output: Indice dell'errore: 10
Throws Exception
Qualsiasi metodo può essere programmato per lanciare manualmente le proprie eccezioni.
“int calculate(int num) throws ArithmeticException” lancia un'eccezione.Esempio
public class ExceptionSample {
public static void main (String args [ ]) {
try { int b= 0; calculate( b );} //call the function, but exception occurs!
catch( Exception e) {
System.out.println("L'errore è"+ e.getMessage( ));
}}
public static int calculate(int num) throws ArithmeticException { // throws exception manually
int a=10, c; c = a/num; // num is 0, error!
return c;
}
}
SINTASSI
public class |ExceptionSample|{
public static void main (String args [ ]) {
try {int |b|=|0|; calculate( |b| );} //chiama la funzione, ecco una eccezione!
catch( |Exception e|) {
System.out.println("|L'errore è|"+ e.getMessage( ));
}}
public static int |calculate|(int |num|)
throws |ArithmeticException|{ // lancia manualmente l'eccezione
int |a|=|10|, |c|; |c| = |a|/|num|; // num è zero, errore!
return |c|;
}
}Output: L'errore è: / per zero.)
Spiegazione
La Classe File
La classe file si usa per motrare le proprietà del file,per controllare se esiste, aw è scrivibile,leggibile, e per rinominarlo
File f = new File (nome_file); // crea un oggetto file
f.exists(); // controlla se esiste
f.canRead( ); // controlla se è leggibile
f.canWrite( ); // controlla se è scrivibile
f.isfile( ); // controlla se è un file
Esempio
File f = new File ( MyFile );
if (f.exists( )) {
System.out.println(“Esiste:”+ f.exists()); // Esiste: true (vero)
System.out.println(“Leggibile:”+ f.canRead()); // Leggibile:true (vero)
System.out.println(“Scrivibile:”+ f.canWrite()); // SCrivibile: false
System.out.println(“È un file:”+ f.isFile()); // È un file: True (vero)
SINTASSI
File |f| = new File ( |MioFile| );
if (|f|.exists( )) {
System.out.println(“|Esiste:|”+ |f|.exists()); // Esiste: true (vero)
System.out.println(“|Leggibile:|”+|f|.canRead());//Leggibile:true (vero)
System.out.println(“|Scrivibile:|”+|f|.canWrite()); // SCrivibile: false
System.out.println(“|È un file:|”+|f|.isFile());//È un file: True (vero)
}
Spiegazione:tutti i metodi precedenti restituiscono True o False
La classe FileOutputStream si usa per elaborare Output stream.FileOutputStream
FileOutputStream fout = new FileOutputStream (nomefile);
System.in.read( ); // legge i caratteri immessi
fout.write( ); // scrive i caratteri nel file
“new FileIOutputStream (file-name)” // crea un Output stream.
“System.in.read( );” // legge i caratteri immessi dalla tastiera.
Esempio
Prepara un file vuoto “MioFile.txt” nella stessa cartella del progetto con il file OutputFile.java
package mioPackage;
import java.io.*;
public class OutputFile {
public static void main(String[] args) {
char ch;
int number;
try{
FileOutputStream fout = new FileOutputStream("MioFile.txt");
System.out.println("Immettete qualche parola, finite con il segno # e date immissine:");
while((ch = (char)System.in.read())!= '#') // legge i caratteri immessi dalla tasiera
fout.write(ch); // scrive i caratteri nel file
fout.close();
}
catch(FileNotFoundException e){
System.err.println(e);
}
catch(IOException e){
System.err.println(e);
}
}
}SINTASSI
Preparate un file vuoto “|MIOFILE.TXT|” nella stessa cartella del progetto del file OutputFile.java
package |mioPackage|;
import java.io.*;
public class OutputFile {
public static void main(String[] args) {
char |ch|;
int |number|;
try {
FileOutputStream |fout| = new FileOutputStream("|MioFile.txt|");
System.out.println("|Immettete qualche parola, finite con il segno # e date immissione:|");
while((|ch| = (char)System.in.read())!= '#') // legge i caratteri immessi dalla tastiera
|fout|.write(|ch); // scrive i caratteri nel file
|fout|.close();
}
catch(FileNotFoundException e){ System.err.println(e);}
catch(IOException e){
System.err.println(e);
} } }
Procedimento e spiegazione
FileInputStream
La classe FileInputStream viene utilizzata per elaborare il flusso di input.
FileInputStream fin = nuovo FileInputStream (nome file);
fin.read (); // legge il contenuto di un file
"new FileInputStream (nome-file)" // crea un flusso di input
"Fin.read ();" // legge il contenuto di un file
Esempio
Dato che il contenuto di MyFile.txt, che risiede nella stessa cartella del file InputFile.java, sia “C++ è molto buono!”
package myPackage;
import java.io.*;
public class InputFile {
public static void main(String[] args) {
char ch;
int number;
try{
FileInputStream fin = new FileInputStream("MyFile.txt");
while((number=fin.read())!= -1) // legge il file
System.out.print((char)number); // li cambia in 'char'
fin.close();
}
catch(FileNotFoundException e){
System.err.println(e);
}
catch(IOException e){
System.err.println(e);
}}}
SINTASSI
package |mioPackage|;
import java.io.*;
public class InputFile {
public static void main(String[] args) {
char |ch|;
int |number|;
try{
FileInputStream |fin| = new FileInputStream("|MioFile.txt|");
while((number=|fin|.read())!= |-1|) // legge il file
System.out.print((char)|number|); // li cambia in 'char'
|fin|.close();
}
catch(FileNotFoundException e){
System.err.println(e);
}
catch(IOException e){
System.err.println(e);
}}}
Output: C++ è molto buono!
Spiegazione: