logo

Java-kast undantag

I Java tillåter undantag oss att skriva koder av god kvalitet där felen kontrolleras vid kompileringstillfället istället för vid körning och vi kan skapa anpassade undantag som gör kodåterställning och felsökning enklare.

Java-kast nyckelord

Nyckelordet Java throw används för att skapa ett undantag uttryckligen.

linux ändra katalognamn

Vi specificerar undantag föremål som ska kastas. Undantaget har ett meddelande med sig som ger felbeskrivningen. Dessa undantag kan vara relaterade till användarinmatningar, server etc.

Vi kan kasta antingen markerade eller omarkerade undantag i Java genom att använda nyckelordet throw. Det används främst för att skapa ett anpassat undantag. Vi kommer att diskutera anpassade undantag senare i det här avsnittet.

Vi kan också definiera vår egen uppsättning villkor och skapa ett undantag uttryckligen med hjälp av nyckelordet throw. Till exempel kan vi kasta ArithmeticException om vi dividerar ett tal med ett annat tal. Här behöver vi bara ställa in villkoret och kasta undantag med hjälp av nyckelordet throw.

Syntaxen för nyckelordet Java throw ges nedan.

kasta instans, dvs.

 throw new exception_class('error message'); 

Låt oss se exemplet med throw IOException.

arp-a kommando
 throw new IOException('sorry device error'); 

Där instansen måste vara av typen Throwable eller underklass av Throwable. Exception är till exempel underklassen till Throwable och de användardefinierade undantagen utökar vanligtvis klassen Exception.

Java throw nyckelord Exempel

Exempel 1: Kasta omarkerat undantag

I det här exemplet har vi skapat en metod som heter validate() som accepterar ett heltal som en parameter. Om åldern är mindre än 18, slänger vi ArithmeticException annars skriv ut ett meddelande välkommen att rösta.

TestThrow1.java

I det här exemplet har vi skapat valideringsmetoden som tar heltalsvärde som en parameter. Om åldern är mindre än 18, slänger vi ArithmeticException annars skriv ut ett meddelande välkommen att rösta.

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

Produktion:

Java-kast nyckelord

Exempel 3: Kasta användardefinierat undantag

undantag är allt annat under klassen Throwable.

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

Produktion:

Java-kast nyckelord