J'essaye d'obtenir une exception spécifique
Entrée H = -1; B = 2;
Production attendue
java.lang.Exception: la largeur et la hauteur doivent être positives
Sortie courant
-2
public class Solution {
static int H,B;
static boolean flag = true;
static //static initializer block
{
Scanner sc = new Scanner(System.in);
H=sc.nextInt();
B=sc.nextInt();
}
public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}
}
}
Comment puis-je obtenir cette exception spécifique?
3 Réponses :
Vous pouvez lancer votre propre exception comme ceci
if(H<0 || B<0){
throw new IllegalArgumentException("Breadth and height must be positive");
}
Cependant, il serait préférable d'utiliser quelque chose comme une IllegalArgumentException pour cela.
if(H<0 || B<0){
throw new Exception("Breadth and height must be positive");
}
Notez que "0" est une réponse valide pour une zone (et 0 n'est pas négatif), donc <0 pas <1
Ajoutez ceci comme premières lignes de votre méthode principale:
if(B < 1 || H < 1) {
throw new Exception("Breadth and height must be positive");
}
Ajoutez une instruction throw . Vous pouvez l'ajouter dans un bloc try catch ou ajouter à la place une exception throws (ou une exception plus spécifique) à la signature de la méthode (cette dernière est illustrée ci-dessous):
import java.util.Scanner;
public class Solution {
static int H,B;
static boolean flag = true;
//static initializer block
static {
Scanner sc = new Scanner(System.in);
H = sc.nextInt();
B = sc.nextInt();
if (H < 0 || B < 0) {
try {
throw new Exception("Breadth and height must be positive");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (flag) {
int area = B * H;
System.out.print(area);
}
}
}
Ou vous pouvez mettre le bloc try avec l'instruction throw dans votre bloc d'initialisation statique:
import java.util.Scanner;
public class Solution {
static int H,B;
static boolean flag = true;
//static initializer block
static {
Scanner sc = new Scanner(System.in);
H = sc.nextInt();
B = sc.nextInt();
}
public static void main(String[] args) throws Exception {
if (flag) {
if (H < 0 || B < 0) {
throw new Exception("Breadth and height must be positive");
} else {
int area = B * H;
System.out.print(area);
}
}
}
}
Ajoutez simplement si B ou H sont négatifs puis lancez une nouvelle exception (vous mettez le messega spécifique dans le constructeur).