User Tools

Site Tools


tutorial:command_exceptions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Next revisionBoth sides next revision
tutorial:command_exceptions [2022/08/08 02:17] solidblocktutorial:command_exceptions [2022/09/18 13:39] nexus-dino
Line 7: Line 7:
 Below is a coin flip command to show an example of exceptions in use. Below is a coin flip command to show an example of exceptions in use.
  
 +For 1.18 and below:
 <code java [enable_line_numbers="true"]> <code java [enable_line_numbers="true"]>
 dispatcher.register(literal("coinflip") dispatcher.register(literal("coinflip")
     .executes(ctx -> {     .executes(ctx -> {
-        Random random = new Random();+        Random random = Random.create(); 
 +  
 +        if(random.nextBoolean()) { // If heads succeed. 
 +            ctx.getSource().sendMessage(Text.translatable("coin.flip.heads")) 
 +            return Command.SINGLE_SUCCESS; 
 +        } 
 + 
 +        throw new SimpleCommandExceptionType(new TranslatableText("coin.flip.tails")).create(); // Oh no tails, you lose. 
 +    })); 
 +</code> 
 + 
 +Though you are not just limited to a single type of exception as Brigadier also supplies Dynamic exceptions which take additional parameters for context. 
 + 
 +<code java [enable_line_numbers="true"]> 
 +DynamicCommandExceptionType used_name = new DynamicCommandExceptionType(name -> { 
 +    return new LiteralText("The name: " + (String) name + " has been used"); 
 +}); 
 +</code> 
 + 
 +For 1.19 and above: 
 +<code java [enable_line_numbers="true"]> 
 +dispatcher.register(literal("coinflip"
 +    .executes(ctx -> { 
 +        Random random = Random.create();
   
         if(random.nextBoolean()) { // If heads succeed.         if(random.nextBoolean()) { // If heads succeed.
tutorial/command_exceptions.txt · Last modified: 2024/04/15 06:43 by solidblock