logo

Java-heittopoikkeus

Javassa poikkeusten avulla voimme kirjoittaa hyvälaatuisia koodeja, joissa virheet tarkistetaan käännösaikana ajon aikana, ja voimme luoda mukautettuja poikkeuksia, jotka helpottavat koodin palauttamista ja virheenkorjausta.

Java-heitto-avainsana

Java-heitto-avainsanaa käytetään poikkeuksen heittämiseen eksplisiittisesti.

java muuntaa merkki merkkijonoksi

Määrittelemme poikkeus esine, joka on tarkoitus heittää. Poikkeuksessa on jokin viesti, joka sisältää virheen kuvauksen. Nämä poikkeukset voivat liittyä käyttäjän syötteisiin, palvelimeen jne.

Voimme heittää joko valittuja tai tarkistamattomia poikkeuksia Javassa heitto-avainsanalla. Sitä käytetään pääasiassa mukautetun poikkeuksen tekemiseen. Käsittelemme mukautettuja poikkeuksia myöhemmin tässä osiossa.

Voimme myös määritellä omat ehtomme ja heittää poikkeuksen eksplisiittisesti käyttämällä throw-avainsanaa. Voimme esimerkiksi heittää ArithmeticExceptionin, jos jaamme luvun toisella luvulla. Tässä meidän täytyy vain asettaa ehto ja heittää poikkeus käyttämällä throw-avainsanaa.

Java-heitto-avainsanan syntaksi on annettu alla.

heittoinstanssi eli

 throw new exception_class('error message'); 

Katsotaanpa esimerkkiä heittää IOException.

 throw new IOException('sorry device error'); 

Kun ilmentymän on oltava tyyppiä Throwable tai Throwable-alaluokkaa. Esimerkiksi Exception on Throwable-luokan alaluokka, ja käyttäjän määrittämät poikkeukset yleensä laajentavat Exception-luokkaa.

Java-heitto-avainsana Esimerkki

Esimerkki 1: Heittäminen valitsematon poikkeus

Tässä esimerkissä olemme luoneet menetelmän nimeltä validate(), joka hyväksyy parametriksi kokonaisluvun. Jos ikä on alle 18, jätämme aritmeettisen poikkeuksen, muuten tulosta viesti tervetuloa äänestämään.

TestThrow1.java

Tässä esimerkissä olemme luoneet validointimenetelmän, joka ottaa parametrina kokonaisluvun arvon. Jos ikä on alle 18, jätämme aritmeettisen poikkeuksen, muuten tulosta viesti tervetuloa äänestämään.

 public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age<18) { throw arithmetic exception if not eligible to vote new arithmeticexception('person is vote'); } else system.out.println('person vote!!'); main method public static void main(string args[]){ calling the function validate(13); system.out.println('rest of code...'); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/exception-handling/63/java-throw-exception.webp" alt="Java throw keyword"> <p>The above code throw an unchecked exception. Similarly, we can also throw unchecked and user defined exceptions.</p> <h4>Note: If we throw unchecked exception from a method, it is must to handle the exception or declare in throws clause.</h4> <p>If we throw a checked exception using throw keyword, it is must to handle the exception using catch block or the method must declare it using throws declaration.</p> <h3>Example 2: Throwing Checked Exception</h3> <h4>Note: Every subclass of Error and RuntimeException is an unchecked exception in Java. A checked exception is everything else under the Throwable class.</h4> <p> <strong>TestThrow2.java</strong> </p> <pre> import java.io.*; public class TestThrow2 { //function to check if person is eligible to vote or not public static void method() throws FileNotFoundException { FileReader file = new FileReader(&apos;C:\Users\Anurati\Desktop\abc.txt&apos;); BufferedReader fileInput = new BufferedReader(file); throw new FileNotFoundException(); } //main method public static void main(String args[]){ try { method(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println(&apos;rest of the code...&apos;); } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/exception-handling/63/java-throw-exception-2.webp" alt="Java throw keyword"> <h3>Example 3: Throwing User-defined Exception</h3> exception is everything else under the Throwable class. <p> <strong>TestThrow3.java</strong> </p> <pre> // class represents user-defined exception class UserDefinedException extends Exception { public UserDefinedException(String str) { // Calling constructor of parent Exception super(str); } } // Class that uses above MyException public class TestThrow3 { public static void main(String args[]) { try { // throw an object of user defined exception throw new UserDefinedException(&apos;This is user-defined exception&apos;); } catch (UserDefinedException ude) { System.out.println(&apos;Caught the exception&apos;); // Print the message from MyException object System.out.println(ude.getMessage()); } } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/exception-handling/63/java-throw-exception-3.webp" alt="Java throw keyword"> <hr></18)>

Lähtö:

merkkijonon muunnos int:ksi javassa
Java-heitto-avainsana

Esimerkki 3: Heitto käyttäjän määrittämä poikkeus

poikkeus on kaikki muu Throwable-luokan alla.

TestThrow3.java

 // class represents user-defined exception class UserDefinedException extends Exception { public UserDefinedException(String str) { // Calling constructor of parent Exception super(str); } } // Class that uses above MyException public class TestThrow3 { public static void main(String args[]) { try { // throw an object of user defined exception throw new UserDefinedException(&apos;This is user-defined exception&apos;); } catch (UserDefinedException ude) { System.out.println(&apos;Caught the exception&apos;); // Print the message from MyException object System.out.println(ude.getMessage()); } } } 

Lähtö:

Java-heitto-avainsana