Java Kusiyanisa uye Maitiro Ekuzvibata

Semugadziri weJava, iwe unofanirwa kuve neruzivo rwakanaka nezve Java kusarudzika uye kubata kwakasarudzika.

Iyi dzidziso inopa ruzivo rwekutanga runofanirwa kuve rwese mugadziri pavanenge vachishanda nezvirongwa zveJava. Kutanga, ngatitange nekunzwisisa izvo chaizvo izvo Java Kusiyanisa kuri.

Ndezvipi Java Kusarudzika

Iyo Java chirongwa inogona kumhanyisa mumatambudziko anokonzeresa kuti chirongwa chimbomiswa kamwe kamwe panguva yekuitwa kwayo. Matambudziko aya anonzi anosarudzika.

Anogadzira programmer anokwanisa kukwanisa kuona zvikanganiso zvinogona kuitika panguva yekuurayiwa uye nekupa dzimwe nzira dzechirongwa kutora kana zvadai. Iyi tsika inodaidzwa kunzi kubata.

Iye zvino unogona kunge uchinetseka kuti nei tichida kunze kwekubata zvachose. Wadii kunyora zvirongwa zvisingakande kunze?

Nei Tichida Kunze kwekubata

Sezvazvinoitika, kunyora mapurogiramu asingazokanda kunze hakusi nyore sezvazvinonzwika. Kazhinji yenguva, izvi zvikanganiso zvisingadzivisike zviri kunze kwekutonga kwamugadziri.



Zvirongwa zvinogamuchira zvinoshandiswa nemushandisi zvinowanzo mhanya mukusiiwa nekuda kwekuisa kwakakodzera kunopihwa nemushandisi. Saka kuverenga mafaera ekunze uchifunga mukana wekuti akatamiswa, kutumidzwazve zita, kana kubviswa nechokunze sosi pasina ruzivo rwemugadziri.

Mumamiriro ezvinhu akadaro, chirongwa ichi chinofanira kukwanisa kubata zvakasarudzika zvine mutsindo pasina kumisa kuuraya.

Hierarchy yeJava Kunze

Zvese zvinosarudzika muJava zvinofanirwa kunge zviri mwana we Exception kirasi, iyo pachayo iri mwana we Throwable kirasi.

Zvinyorwa zviviri zvidiki zve Exception kirasi iri RuntimeException uye IOException.

Kunze vs Kukanganisa

Rimwe boka revana re Throwable kirasi ndiyo Error kirasi. Nekudaro, kukanganisa kwakasiyana nekusiiwa.

Zvikanganiso zvinoratidza matambudziko ayo JVM angamhanye nawo mukati mekuitwa. Aya matambudziko anowanzo kuve akaomarara uye asingadzoreke. Ndangariro dzinodonha uye kusaenderana muraibhurari nyaya ndizvo zvakajairika zvikonzero zvezvikanganiso muzvirongwa

StackOverflowError uye OutOfMemoryError iyi mienzaniso miviri yeJava Zvikanganiso.

Wakatariswa uye Unchecked Kunze

Tinogona kupatsanura Java Kusarudzika muzvikamu zviviri zvikuru: checked uye kusagadziriswa kusara.

Kuongororwa kusarudzika ndiko kusarudzika kunoda kugadziriswa muchirongwa usati wanyora. Kana izvi zvisizvo zvisina kubatwa, chirongwa ichi hachizonyorwa neye Java compiler. Naizvozvo, izvi zvinodaidzwa zvakare kunzi-nguva-kunze. IOExceptions mienzaniso yakanaka yezvakatariswa kunze.

Kusatenderwa kusarudzika ndiko kusarudzika kunofuratirwa nemutengesi kana uchinyora chirongwa. Kunyangwe isu takabata aya akasarudzika muchirongwa kana kwete hazvina basa kana chirongwa ichi chaunganidzwa. Sezvo kubata kwakasarudzika kusingaisirwe pane izvi zvinosara, chirongwa chedu chinogona kumhanyisa mu RuntimeExceptions izvo zvinoguma nekugumisa chirongwa.

Makirasi ese anowedzera RuntimeException kirasi haina kuongororwa. Mienzaniso miviri yemakirasi akadaro i NullPointerException uye ArrayIndexOutOfBoundsException.

Dzinowanzo Shandiswa Nzira muKusarudzika Kirasi

Tichaenda kuburikidza nenzira dzino vashoma dzinowanzo shandiswa muJava Exception kirasi:

  1. getMessage: inodzosera meseji ine ruzivo nezve iyo yakasara yakaitika.
  2. printStackTrace: inodzosera iyo trace trace yeiyo yakasarudzika yakaitika.
  3. toString: inodzosera zita rekirasi uye meseji iyo inodzoserwa ne getMessage nzira.

Maitiro Ekubata Kunze

Ngatione kuti tingaite sei kunze kweJava:

edza-bata

Tinogona kubata zvisaririra uye tozvibata nemazvo tichishandisa edza-bata block muJava.

Mune syntax iyi, chikamu chekodhi chinokanda kukanda chakasarudzika chakaiswa mukati mekuyedza block uye inobata block / mabhuroko anobata chakakandwa kunze / kunze uye unoibata maererano nepfungwa dzatinopa.

Iyo yekutanga syntax yeyedza-kubata block inotevera.

try {
//exception-prone code } catch(Exception e) {
//error handling logic }

Nemaitiro aya, chirongwa hachimise kuuraya kana chakasarudzika chakakandwa nechirongwa, pachinzvimbo, chinobatwa nenyasha.

Tichaona maitiro ekubata IOExceptions | yakakandwa ne FileReader kirasi muchirongwa cheJava.

Muenzaniso:

import java.io.FileReader; public class TryCatchBlockExample {
public static void main(String[] args) {

try {

FileReader file = new FileReader('source.txt');

file.read();
}
catch(Exception e) {

e.printStackTrace();
}
} }

Pano, isu tashandisa imwechete yekubata block kubata FileNotFoundException kukandwa kana uchisimbisa iyo FileReader kirasi uye IOException yakakandwa ne read() nzira ye FileReader kirasi.

Ose maviri aya anosarudzika vana ve Exception kirasi.

Tinogona zvakare kushandisa akawanda ekubata zvirevo kubata mhando dzakasiyana dzezvikanganiso zvakakandwa nekodhi mukati meimwe chete test chirevo. Semuenzaniso wapfuura, tinogona kushandisa imwechete yekubata kubata iyo FileNotFoundException uye chimwe chinobata che IOException seyinotevera kodhi snippet inoratidza:

import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class TryCatchBlockExample {
public static void main(String[] args) {

try {

FileReader file = new FileReader('source.txt');

file.read();

file.close();
}
catch(FileNotFoundException e) {

e.printStackTrace();
}
catch(IOException e) {

e.printStackTrace();
}
} }

Kana iyo yakasarudzika inowirirana neakasarudzika inobatwa neyekutanga yekubata chirevo, inobatwa ipapo nepfungwa mukati mekutanga kubata chirevo.

Kana izvo zvinosarudzika zvisingaenderane, zvinopfuudzwa kune yechipiri kubata chirevo. Kana paine zvirevo zvinopfuura zviviri zvekubata, maitiro aya anoenderera mberi kudzamara kusara kwasvika chirevo chekubata chinobata mhando yacho.

Kubva FileNotFoundException chidimbu che IOException, uchishandisa yechipiri kubata chirevo kubata FileNotFoundException hazvishande. Ichabatwa neyekutanga bata chirevo uye usambosvika chirevo chechipiri.

Ongorora:Izvo zvinomanikidzwa kushandisa kanokwana kamwe chete chirevo chekubata ine chirevo chekuyedza.

pakupedzisira

Patinoshandisa a edza-bata block kuti tibate zvakasarudzika muchirongwa chedu, pane zviitiko zvatinoda kuita zvimwe zvine musoro kunyangwe hazvo kana chakasarudzika chakabatwa kana kwete. Mumamiriro ezvinhu akadaro, tinogona kushandisa edza-bata-pakupedzisira block panzvimbo pekungori a edza-bata bhuroka.

Ipapo, kodhi iri mukati me finally chirevo chinoitwa kuti kana chisaririra chikaitika kana kwete. I finally chirevo chinofanira kugara chichiuya pakupera kwekuyedza-kubata-kwekupedzisira block.

Semuenzaniso, patinoshandisa iyo FileReader kirasi kuti uverenge faira, zvakakosha kuti uvhare iyo yakavhurwa faira pakupera kwekugadzirisa kunyangwe yakasarudzika ikaitika kana kwete. Kuti tione izvi, tinogona kuisa kodhi yekuvhara iyo faira mukati me finally chirevo.

import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class TryCatchFinallyBlockExample {
public static void main(String[] args) {
FileReader file = null;
try {

file = new FileReader('source.txt');

file.read();
}
catch(FileNotFoundException e) {

e.printStackTrace();
}
catch(IOException e) {

e.printStackTrace();
}
finally {

file.close();
}
} }

Nekudaro, kana iwe ukaedza kuumbiridza kodhi iri pamusoro, kodhi yacho haizo nyorwa nekuda kweisina kusungwa IOException. Izvi zvinodaro nekuti close() nzira ye FileReader kirasi inogona zvakare kukanda IOExceptions. Nekudaro, isu tinofanirwa kuisa chikamu ichi mukati meimwe kuyedza block seizvi:

import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class TryCatchFinallyBlockExample {
public static void main(String[] args) {
FileReader file = null;

try {

file = new FileReader('source.txt');

file.read();
}
catch(FileNotFoundException e) {

e.printStackTrace();
}
catch(IOException e) {

e.printStackTrace();
}
finally {

try {


file.close();

}

catch(IOException e) {


e.printStackTrace();

}
}
} }

anokanda

Kubata zvikanganiso uchishandisa throws kiyi muJava iri nyore. Muchokwadi, mune iyi nzira, haunyatso bata kunze kwenzvimbo kwainoitika. Panzvimbo iyoyo, isu tinokanda kunze kunze kwenzira yazvino kunzira iyo yaidaidza nzira yazvino. Ipapo, kuendesa iko kukanganisa kunova iko kuita kwenzira yekunze.

Kukanda chisaririra kunze kwenzira, iwe unofanirwa kungozivisa kuti nzira iyi inogona kukanda yakasarudzika inosarudzika. Ngatione kuti tingabata sei IOExceptions yakakandwa ne FileReader kirasi uchishandisa nzira iyi.

Muenzaniso:

import java.io.FileReader; import java.io.IOException; public class ThrowsExample {
public void readFile throws IOException {
FileReader file = new FileReader('source.txt');
file.read();
file.close();
} }

kukanda

Kusiyana nedzimwe nzira dziri mune ino runyorwa, iyo throw keyword harishandiswe kubata zvikanganiso. Asi sezvo vanhu vazhinji vachivhiringidza iyo throw kiyi ne throws kiyi, isu takafunga kuti zvingave zvakanaka kuti tikurukure pano.

I throw kiyi kiyi inoshandiswa kunyatso tsanangura kusarudzika. Tinogona kukanda kunze kuchangobva kusimbiswa kana chakasarudzika chakabatwa mukati medzidziso.

public class ThrowExample {
public void invalidate(int amount) throws Exception {
if (amount < 500) {

throw new Exception('Amount not sufficient');
}
} }

Mushandisi-Anotsanangurwa Kusarudzika

Pamusoro pekushandisa yakavakirwa-mukati Java kusiyanisa, unogona kutsanangura zvako wega kunze. Unogona kuvatsanangudza sekutarisa kana kusatariswa kusarudzika. Kugadzira yakasarudzika nyowani, yako nyowani yakasarudzika inofanira kuwedzera Exception kirasi.

Kugadzira unckecked kunze, wedzera iyo RuntimeException kirasi.

Mune inotevera kodhi muenzaniso, isu takagadzira mushandisi-akatsanangurwa akatariswa kunze:

public class InvalidLengthException extends Exception {
private int length;
private String message;
public InvalidLengthException(int length, String message) {
this.length=length;
this.message=message;
}
public int getAmount() {
return this.length;
}
public String getMessage() {
return this.message;
} }

Iye zvino tinogona kushandisa iri pamusoro pamusoro pechirongwa chedu pfungwa seizvi:

public class InputChecker {
private int minLength;
private int maxLength;
public InputChecker(int minLength, int maxLength) {
this.minLength=minLength;
this.maxLength=maxLength;
}
public void checkStringLength(String strInput) throws InvalidLengthException {
int strLength = strInput.length();
if (strLength maxLength){

throw new InvalidLengthException(strLength, 'Input should have maximum '+maxLength+' character');
}
} }

Kana isu tikatarisa kureba kwetambo tichishandisa InputChecker kirasi, ichakanda InvalidLengthException kana tambo kureba kuri pazasi pehurefu hushoma kana pamusoro pehurefu hwakareba.

public class Main {
public static void main(String[] args) {
InputChecker ic = new InputChecker(2, 7);
try {

ic.checkStringLength('longer than the maximum length');
}
catch(InvalidLengthException e) {

e.printStackTrace();
}
} }

Kana isu tichimhanya pamusoro apa kodhi snippet, iyo inokanda InvalidLengthException uye isu tichawana zvinotevera kuburitsa:

InvalidLengthException: Input should have maximum 7 character
at InputChecker.checkStringLength(InputChecker.java:17)
at Main.main(Main.java:6)

Mhedziso

Mune ino dzidziso, isu takakupa iwe inokurumidza uye yakapfupika sumo kune Java Kunze. Isu tinoshuvira kuti iwe ikozvino wave nekunzwisisa kwakanaka kwezvisipo uye nemabatiro aungaita nazvo mune yako Java chirongwa.